Using GraphQL in JSS Next.js apps

Version:

If you want to use GraphQL in your JSS Next.js app, you can initialize your application with all the infrastructure prepared for querying Sitecore GraphQL endpoints.

Important

You cannot use GraphQL if your app is running in disconnected mode. Instead, make sure that:

  • Your app's fetch method is set to REST.

  • Your app includes the nextjs-styleguide addon.

To create a Next.js application that uses the JSS GraphQL API for fetching data, you can provide the --fetchWith parameter to the JSS CLI command jss create.

For example, if you create a code-first JSS app based on the Next.js sample application, run the command:

jss create my-next-app nextjs --fetchWith GraphQL [--prerender SSG|SSR]

To provide the --fetchWith parameter when creating a project with the Sitecore Containers template for Next.js, use the command:

dotnet new sitecore.nextjs.gettingstarted -n MyProject --JSSCreateParams "--fetchWith GraphQL [--prerender SSG|SSR]"

If you created your Next.js JSS app with the default parameters, you can use the sample JSS Next.js app to switch to GraphQL.

To write type-protected code with rich IDE assists using GraphQL types and TypeScript static data typing, you can introspect the GraphQL schema.

In addition to getting Sitecore data with the JSS GraphQL API, you can also query GraphQL endpoints in a similar manner to what you do when developing regular JavaScript applications using connected GraphQL. You can use connected GraphQL to run GraphQL queries at the component level.

If you have suggestions for improving this article, let us know!