Troubleshooting JSS Next.js apps
To help you debug your JSS application, we recommend you use the debug logging utilities provided by JSS.
You can prevent most errors by doing the following:
-
Verify that all environment variables used by the app have values. The sample app searches for environment variables in the following order:
-
scjssconfig.json. -
.env. -
.env.local(for local environments only).
-
-
If multiple files contain a definition of the same variable, the application uses the last value it finds.
Refer to the sample
.envfile for variable names and descriptions. -
Check that you have correctly set up the API key.
-
Check that your project's site definition and app definition are correct in your Sitecore configuration. Refer to the Sitecore app configuration for the list of required properties.
-
Verify that you have set the JSS Editing Secret. The
JSS_EDITING_SECRETvalue used by your Next.js app must match the value used by your Sitecore instance. -
Verify that the GraphQL endpoint is correct in
package.jsonand the Sitecore app configuration. Try opening the GraphQL IDE in a browser, using values from your config (<sitecore hostname + graphQL endpoint>/ui?sc_apikey=<api key>) to make sure the endpoint is working.
Server-side JavaScript errors
If you encounter unexpected JavaScript errors during the npm install or build steps, especially errors that other team members cannot reproduce, check the Node versions and npm being used. From a terminal, run:
node -v
npm -vWe test JSS using the Long Term Support (LTS) Node version. These are typically one major version behind the latest official Node version.
The Node/npm version used by your CI/Production environments might differ from that of your local environment. When a project configuration does not require a specific Node/npm version in package.json, deployment agents commonly build using the most recent or an environment-specific default version.
If you need to swap between multiple Node versions on your local environment for testing, you can use third-party packages like n or nvm.
Errors regarding SSL certificates
If you are working with a local Sitecore instance using a privately signed certificate, you might experience the following error:
Error: unable to verify the first certificate
Error: UNABLE TO VERIFY LEAF SIGNATURE
UnauthorizedError: invalid signatureTo resolve this error, configure Sitecore CA certificates for Node.js.
Errors deploying a JSS app locally
If the import role does not have the correct permissions, you might experience the following error:
IMPORT ERROR(S) OCCURRED!
Exception thrown while importing JSS app
Exception: Sitecore.Exceptions.AccessDeniedException
Message: AddFromTemplate - Add access requiredRefer to Errors when importing JSS application on Azure for the solution.
Data-fetching issues
Building and rendering a JSS Next.js app depends on successfully fetching data using GraphQL. The most common cause of failed builds and apps that cannot render pages is an issue with the data-fetching process.
You can use the GraphQL IDE at <sitecore hostname + graphQL endpoint>/ui?sc_apikey=<api key> to diagnose issues with the data-fetching process.
To support static generation functionality, the Next.js JSS app uses a GraphQL query to retrieve Sitecore paths. Try running the following query in the GraphQL IDE:
# YOUR_PATH should be the ID of your site root (home page) in lower-case, with dashes removed.
# YOUR_LANGUAGE should be your default language, as defined in package.json
query{
search(where: {
AND:[
{
name:"_path",
value:"YOUR_PATH"
},
{
name:"_language",
value:"YOUR_LANGUAGE"
},
{
name:"_hasLayout",
value :"true"
}
]
})
{
total
results {
url {
path
}
}
}"
}If you do not see the expected results, try the following steps:
-
In the Sitecore Control Panel, use Populate Solr Managed Schema to populate the Solr Schema.
-
In the Sitecore Control Panel, use Indexing Manager to rebuild indexes.
-
Check that your content items have versions for the language you are querying.
Error when trying to edit items in Sitecore
After creating a new user in the Sitecore Editor Role, attempting to edit the JSS app items in Sitecore might warn that the user does not have read access rights.
The workaround is to set Workflow State Write for the System/Workflows/JSS development workflow item manually, enabling the Published state, which is final, to be editable. It allows the user to create a new version of an item for editing using the Lock and Edit option.
Rendering host timeout issue in Experience Editor
When opening a JSS app configured to use the HTTP rendering engine (such as a Next.js app) for the first time using the Experience Editor, you might get a timeout error from the rendering host with the message The operation has timed out. In the logs, you can see the following:
10292 10:51:16 ERROR [JSS] Error occurred during POST to remote rendering host: `http://localhost:3000/api/editing/render`
10292 10:51:16 ERROR The operation has timed out
Exception: System.Net.WebException
Message: The operation has timed out
Source: System
at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
at System.Net.WebClient.UploadString(Uri address, String method, String data)
at Sitecore.JavaScriptServices.ViewEngine.Http.RenderEngine.Invoke[T](String moduleName, String functionName, Object[] functionArgs)To resolve the issue, edit the \App_Config\Sitecore\JavaScriptServices\Sitecore.JavaScriptServices.ViewEngine.Http.config file to increase the value of the RequestTimeoutMs setting. For example:
<!-- Specifies the maximum duration, in milliseconds, that your .NET code should wait for requests to the HTTP renderer (for example, the `EndpointUrl` setting) to respond. -->
<RequestTimeoutMs>10000</RequestTimeoutMs>Connection to rendering host failed due to payload size
If you receive the (413) Payload Too Large error when sending a payload to Experience Edge, we recommend you increase the sizeLimit property of your app, which is set to 2MB by default in sample Next.js apps.
You'll need to make this change in the following files:
-
\src\pages\api\editing\render.ts -
\src\pages\api\editing\[key].ts
The following example represents the relevant part of render.ts after increasing the payload size limit to 5MB:
...
export const config = {
api: {
bodyParser: {
sizeLimit: "5mb",
},
responseLimit: false,
},
};
...GraphQL query error when trying to start the Next.js app using a Sitecore instance with SXA
If you have an SXA integration with a Headless Site Collection and you deploy Next.js items in it, you might encounter a GraphQL query error when trying to start the Next.js app in production mode:
Error: Valid value for rootItemId not provided and failed to auto-resolve app root item.
This error occurs because the Next.js app and Next.js app items deployed into the Headless Site Collection reference different templates, causing the query to fail. This error only occurs if you use version 20.x or older of JSS.
To prevent the error, define a rootItemId for your instances of GraphQL services as follows:
-
/src/lib/sitemap-fetcher/plugins/graphql-sitemap-service.ts. -
/src/lib/dictionary-service-factory.ts.
Alternatively, update the JSS NPM packages in your application to version 21 or later. If you encounter the error while running the Next.js application in production mode in your local development environment, you must also upgrade the Headless Services and SXA modules in your local development environment.
Errors when generating GraphQL introspection data
If the GraphQL schema changes, you must regenerate GraphQL introspection data.
In the sample app, you regenerate introspection data using the jss graphql:update command.
Vercel is unable to show data from a local Sitecore environment
If you are using ngrok to expose your local Sitecore endpoint to Vercel, verify that you are using the host-header flag. For example,
ngrok http -host-header=rewrite <your-local-url>Sitecore images don't load on localhost
If your Sitecore images don't load when using a localhost domain for the application, it's probably because you are trying to request images through the Next.js proxy, resulting in the error: 500 - Invalid URI: The hostname could not be parsed.
To load Sitecore images on a localhost domain, set the IncludeServerUrlInMediaUrls attribute of the contents resolver to false to include the Sitecore URL in the image URL. For example:
<config name="jss">
<rendering>
<renderingContentsResolver>
<IncludeServerUrlInMediaUrls>false</IncludeServerUrlInMediaUrls>
</renderingContentsResolver>
</rendering>
</config>With this configuration in place, the application requests the images directly from Sitecore.
In production environments, make sure the value of the IncludeServerUrlInMediaUrls attribute is true. This is the default value.
Experience Editor integration breaks because of a protocol mismatch error
When hosting the Next.js application on platforms other than Vercel, if the integration with Experience Editor stops working because of a protocol mismatch error, override default protocols using the EditingRenderMiddleware.
Editing data cache miss and intermittent 500 errors in Experience Editor
When hosting the Next.js application on platforms other than Vercel, you might see cache miss errors in the Node.js environment. For example:
2022-10-12 16:27:42: Error: Unable to get editing data for preview {"key":"0518d8c6-b7ca-4c73-86c2-a29d971ebeab-2xqnbg0jpx","serverUrl":"https://your-url.com"}
at SitecorePagePropsFactory.createPreviewModePage (/opt/web/.next/server/chunks/9694.js:1190:17)
at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async SitecorePagePropsFactory.create (/opt/web/.next/server/chunks/9694.js:1174:14)
at async getServerSideProps (/opt/web/.next/server/pages/[[...path]].js:1952:17)
at async Object.renderToHTML (/opt/web/.next/node_modules/next/dist/server/render.js:555:20)
at async doRender (/opt/web/.next/node_modules/next/dist/server/base-server.js:1406:38)
at async /opt/web/.next/node_modules/next/dist/server/base-server.js:1501:28
at async /opt/web/.next/node_modules/next/dist/server/response-cache.js:63:36The issue causes a 500 error in the Content Management instance, such as:
3112 16:27:42 ERROR The remote server returned an error: (500) Internal Server Error.
Exception: System.Net.WebException
Message: The remote server returned an error: (500) Internal Server Error.
Source: System
at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
at System.Net.WebClient.UploadString(Uri address, String method, String data)
at Sitecore.JavaScriptServices.ViewEngine.Http.RenderEngine.Invoke[T](String moduleName, String functionName, Object[] functionArgs)Such errors are caused by the instability of the temporary directory used by the editing data cache. To resolve the errors, override the default directory used by the disk-based editing cache implementation.
A large application fails to build because of SitecoreAI Experience Edge rate limits
If you build a very large website using content from SitecoreAI, your build process can fail when exceeding the allowed requests/minute. To resolve this issue, use retries for requests to the SitecoreAI Experience Edge GraphQL endpoint.
Context ID and edge-platform requests
If you're getting errors on requests to endpoints that start with edge-platform, you can troubleshoot the issues. To do so:
-
Using an external client, formulate a request to the relevant endpoint, adding a header
x-sitecore-tracingand setting the value toclient.ImportantThe header is meant for troubleshooting only. Make the call from an external client, like cURL or Postman, and not from an SDK.
-
Send the call. A trace is returned using a new response contract, that overrides the original response, for troubleshooting purposes.
Example response:
{
"originalUrl": "https://edge-platform.sitecorecloud.io/v1/events/v1.2/events?siteId=basicsite",
"originalHeader": {
"x-sitecore-contextid": "1234",
"Content-Type": "application/json",
"Authorization": "Bearer ey",
"User-Agent": "PostmanRuntime/7.34.0",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "****",
"Host": "edge.cloud",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Content-Length": 248
},
"originalBody": {
"clientKey": "",
"channel": "WEB",
"language": "en",
"currencyCode": "USD",
"pointOfSale": "",
"browserId": "abcd",
"friendlyId": "abcd"
},
"destinationRequestUrl": "https://edge-platform.sitecorecloud.io/v1/events/v1.2/events?siteId=basicsite",
"destinationResponseHeaders": {
"x-sitecore-contextid": "1234",
"Content-Type": "application/json",
"Authorization": "Bearer ey",
"User-Agent": "PostmanRuntime/7.34.0",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "****",
"Host": "edge-platform.sitecorecloud.io",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Content-Length": 248
},
"destinatioResponseCode": 400,
"destinationResponseBody": {
"status": 400,
"code": 400,
"message": "No matching constant for [No guest found for client key 9876 and browser id abcd]",
"developerMessage": "400 (Bad Request): No matching constant for [No guest found for client key 9876 and browser id abcd]",
"moreInfo": "Contact Sitecore support here: https://support.sitecore.com"
},
"traceMessages": [
"Looked up and replaced pointOfSale in body, old value '', with new value 'TEST', from 'POS' property in site resource 'resource-site-test' in context 1234",
"Looked up and replaced clientKey in body, old value '', with new value 'someKey', from 'clientKey' property in personalize resource 'resource-site-personalize' in context 1234"
]
}Memory allocation issues in Next.js apps containing large images
If your site includes images that are larger than 10MB, you might experience memory leaks in the rendering host app. This is a known Next.js issue that is awaiting a fix in a future release of the framework—at time of writing, that release is expected to be 14.3.
On earlier versions, you can prevent this issue without needing to shrink your images. To do this:
-
Install the
sharpdependency in your Next.js app using the following command:RequestResponsenpm i sharp -
Redeploy your app.
If you experience this issue on a self-hosted Next.js app, please refer to the relevant Next.js documentation for additional guidance.