Setup a Project with Prismic and Next.js

On this page, you'll learn how to configure a Prismic and Next.js project, including adding dependencies and setting up a Prismic configuration file.

Before you start - Node Version

You need at least Node.js 12.0 or later. Check this by running node -v in your terminal.


1. Launch a new Next.js project

If you don't have an existing Next.js project, then run the following command (Read the full guide for creating a Next app):

  • npx
  • Yarn
Copy
npx create-next-app my-new-nextjs-app
Copy
yarn create-next-app my-new-nextjs-app

Once it is finished, the Create Next app command will install all the dependencies for the default Next.js app. To see your newly created app navigate to the project folder and launch it:

  • npm
  • Yarn
Copy
cd my-new-nextjs-app && npm run dev
Copy
cd my-new-nextjs-app && yarn dev

2. Install the necessary dependencies

The following is a list of dependencies needed to work with Prismic and Next.js, plus what each of them does.

  • npm
  • Yarn
Copy
npm install @prismicio/client prismic-reactjs next-slicezone
Copy
yarn add @prismicio/client prismic-reactjs next-slicezone

What do these dependencies do?

Package

Usage

@prismicio/client

The client is used to query the data from your Prismic repository's API.

prismic-reactjs

This plugin allows you to render Prismic generated data as React components.

next-slicezone

This is a component that matches Prismic Slices with front-end components.

3. Add config and helper files

These files are best practices and are referenced heavily throughout our documentation. The files contain common settings used in your project and helper functions to make creating queries and routing easier.

3.1. Prismic configuration

Create a file called prismicConfiguration.js at the base of your project directory.

Copy
prismicConfiguration.js

This file contains settings that you must configure like your repo name and settings that you must remember to change as your project evolves, i.e. the Link Resolver or Route Resolver.

Add the following code to this file:

Copy
// -- Prismic Repo Name
export const repoName = 'your-repo-name'

// -- Prismic API endpoint
// Determines which repository to query and fetch data from
// Configure your site's access point here
export const apiEndpoint = `https://${repoName}.cdn.prismic.io/api/v2`

// -- Access Token if the repository is not public
// Generate a token in your dashboard and configure it here if your repository is private
export const accessToken = ''

// -- Link resolution rules
// Manages the url links to internal Prismic documents
export const linkResolver = (doc) => {
  if (doc.type === 'page') {
    return `/${doc.uid}`
  }
  return '/'
}

// -- Route Resolver rules
// Manages the url links to internal Prismic documents two levels deep (optionals)
export const Router = {
  routes: [
    {
      "type":"page",
      "path":"/:uid"
    },
  ]
};

Remember to update this file

You will need to add your repo name and update the Link Resolver as your project requires.

3.2. Prismic helpers

Create a prismicHelpers.js file in a folder called utils in your project.

Copy
prismicHelpers.js

This file contains 'helper' functions to make querying the Prismic API simpler in your next.js project.

Add the following code to this file:

Copy
// ~/utils/prismicHelpers.js
import Prismic from '@prismicio/client'
import Link from 'next/link'
import {
  apiEndpoint,
  accessToken,
  linkResolver,
  Router
} from '../prismicConfiguration'

// Helper function to convert Prismic Rich Text links to Next/Link components
export const customLink = (type, element, content, children, index) => (
  <Link
    key={index}
    href={linkResolver(element.data)}
  >
    <a>{content}</a>
  </Link>
)

// -- @prismicio/client initialisation
// Initialises the Prismic Client that's used for querying the API and passes it any query options.
export const Client = (req = null) => (
  Prismic.client(apiEndpoint, createClientOptions(req, accessToken, Router))
);

// Options to be passed to the Client
const createClientOptions = (req = null, prismicAccessToken = null, routes = null) => {
  const reqOption = req ? { req } : {}
  const accessTokenOption = prismicAccessToken ? { accessToken: prismicAccessToken } : {}
  const routesOption = routes ? { routes: Router.routes } : {}
  return {
    ...reqOption,
    ...accessTokenOption,
    ...routesOption,
  }
}

export default Client

3.3. Queries file

Create the queries.js file in the utils folder in your project.

Copy
queries.js

This file contains helper queries to build paths with the getStaticPaths function on dynamic pages like [uid].js that use repeatable Custom Types.

Add the following code to this file:

Copy
// ~/utils/queries.js
async function fetchDocs(page = 1, routes = []) {
  const response = await Client().query('', { pageSize: 100, lang: '*', page });
  const allRoutes = routes.concat(response.results);
  if (response.results_size + routes.length < response.total_results_size) {
    return fetchDocs(page + 1, allRoutes);
  }
  return [...new Set(allRoutes)];
};

/** Fetches all Prismic documents and filters them (eg. by document type).
 *  In production, you would probably query documents by type instead of filtering them.
**/
export const queryRepeatableDocuments = async (filter) => {
  const allRoutes = await fetchDocs()
  return allRoutes.filter(filter)
}

4. Add the Prismic Builder

The Prismic Builder allows you to build Slices and manage Custom Types locally while versioning everything inside your Next.js project.

Run the following command that will configure your project to work with the Prismic Builder:

Copy
npx @slicemachine/init

This command does the following:

1. Connects to a repo

The command will prompt you to create or connect to a Prismic repo. Remember to add this repo name to your prismicConfiguration.js file.

2. Detects your framework

The command will detect the project framework to add the correct plugins.

Adds this dev dependency which is the local builder for creating Slices and Custom Types.

4. Slice Machine script

Adds a slicemachine script in the package.json that's used to run the builder.

5. sm.json

Creates this is the configuration file for your Slice Machine project, it contains the API endpoint and the Slice library location

4.1 Run the Builder

To launch the Builder, run the following command:

  • npm
  • Yarn
Copy
npm run slicemachine
Copy
yarn slicemachine

4.2. Learn how use the Builder

The following article will show you how to build Slices and components using the Prismic Builder.


4.3. Storybook

Storybook acts as a local development environment for your Slices, it will combine your mock data generated by the Prismic Builder with components files so you won't have to slow down and add content to Prismic to test your components.

Read our full documentation


Next steps

Now you have the basic installation needed to query and template content. Use the articles below to learn how to do that:


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Get in touch with us on our Community Forum.