🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Connect your content to Next.js

Assuming you've followed along with the previous steps of configuring schema and editing content, you should be all set up for the next step of bringing your content to the world. Since your content is ultimately just data available through APIs, there’s practically no limit to where you can put it! It doesn’t even have to be the Web, as long as the system can send an HTTP request and do something with the returned JSON data.

In this guide, you will add the necessary code to a Next.js starter to pull in your content from your Sanity Content Lake. Below, you’ll find a simple boilerplate as an embedded CodeSandbox project. If you open it in a new window and start editing, it will fork and be tied to your account if you log in. You can also download the code and run it locally, or import it to your GitHub account. To see the finished code, check out the CodeSandbox embed at the end of this guide.

Follow on CodeSandbox or locally

Next.js requires a server, so this is a CodeSandbox Container. These sandboxes can only be forked if you are logged in. To follow along, we recommend you either log in to CodeSandbox or create an account if you don't have one. Alternatively, you can clone the project from GitHub to your local machine by using the following command:

git clone https://github.com/sanity-io/get-started-sanity-nextjs.git

and then install the dependencies with

npm install.

What you need to know

This guide assumes that you have some prior knowledge of Next.js and React. If you don’t, but want to learn it, then we recommend checking out the official Next.js getting started guide. That being said, this guide has been written intentionally so as to keep the code as simple as possible, so you might be able to tag along here too.

Install the next-sanity toolkit and configure the client

Sanity provides a dedicated toolkit with a lot of built-in functionality for working with content from Sanity in Next.js. In this guide, you’ll only use the client to fetch content.

👉 Add the next-sanity dependency by searching for it by name in CodeSandBox’s dependency box to the left of the code editor. Clicking it will add it to package.json as if you were running npm i next-sanity locally.

Installing dependencies in CodeSandBox using the search functionality

👉 Start by importing the createClient function from next-sanity in the pages/index.js file.

// pages/index.js
import { createClient } from "next-sanity";
export default function IndexPage({ pets }) { return ( <> <header> <h1>Sanity + Next.js</h1> </header> <main> <h2>pets</h2> {pets.length > 0 && ( <ul> {pets.map((pet) => ( <li key={pet._id}>{pet?.name}</li> ))} </ul> )} {!pets.length > 0 && <p>No pets to show</p>} {pets.length > 0 && ( <div> <pre>{JSON.stringify(pets, null, 2)}</pre> </div> )} {!pets.length > 0 && ( <div> <div>¯\_(ツ)_/¯</div> <p> Your data will show up here when you've configured everything correctly </p> </div> )} </main> </> ); } export async function getStaticProps() { const pets = [ /* { _createdAt: "2022-03-08T09:28:00Z", _id: "1f69c53d-418a-452f-849a-e92466bb9c75", _rev: "xnBg0xhUDzo561jnWODd5e", _type: "pet", _updatedAt: "2022-03-08T09:28:00Z", name: "Capybara" } */ ]; return { props: { pets } }; }

👉  If you remove the comments around the object in the pets array, you’ll see how the data is rendered.

👉 The next step is to add a configured client to your Next.js site. Declare a variable named client just above the getStaticProps function in your /pages/index.js file:

import { createClient } from "next-sanity";


const client = createClient();
export async function getStaticProps() { const pets = [ /* { _createdAt: "2022-03-08T09:28:00Z", _id: "1f69c53d-418a-452f-849a-e92466bb9c75", _rev: "xnBg0xhUDzo561jnWODd5e", _type: "pet", _updatedAt: "2022-03-08T09:28:00Z", name: "Capybara" } */ ]; return { props: { pets } }; }

The createClient function takes an object with your configuration, to make it work we need the following properties:

  • projectId: This is the unique identifier for your project that contains all your users, datasets, and other settings. It’s not secret as it’s part of the URL for your content APIs. You’ll find the project ID in the sanity.json file in your studio, or on the project page on sanity.io/manage.
  • dataset: This is a collection of documents within a project. You can have multiple datasets (for example: staging and production).
  • apiVersion: Usually you’d want to put in today’s date YYYY-MM-DD to get the newest version of the query API.
  • useCdn: If you set this to true the client will fetch content from our cache delivery network. In this case, however, we will not generate a whole lot of API traffic, and we want updates to be instantly available, so set this to false
import { createClient } from "next-sanity";


const client = createClient({
projectId: "lqz08o01",
dataset: "production",
apiVersion: "2022-03-25",
useCdn: false
export async function getStaticProps() { const pets = [ { _createdAt: "2022-03-08T09:28:00Z", _id: "1f69c53d-418a-452f-849a-e92466bb9c75", _rev: "xnBg0xhUDzo561jnWODd5e", _type: "pet", _updatedAt: "2022-03-08T09:28:00Z", name: "Capybara" } ]; return { props: { pets } }; }

Querying for content

Now you are ready to replace the hard-coded data with your own.

👉 Start by replacing the array value for pets with the following code:

const pets = await client.fetch(`*[_type == "pet"]`);

Here you can see that we’re using a method on the client called fetch(). We’re passing a simple string as its first argument, and the string is a GROQ query that filters ([]) all (*) your documents down to those with pet as the value for _type. If this query works, it will return an array of documents as objects. Like the one you just removed.

👉 Save your file and see what happens. Did the hardcoded content get replaced by the content you put into the studio? If so, congratulations – you did it! If you add or change the content in the studio and publish it, you should be able to refresh the Next.js preview and see it reflect your updates.

Adding your URL to the Cross-Origins Resource Sharing (CORS) settings

In this example, Next.js will run the code inside of getStaticProps on the server (or in a serverless function if you have deployed it to production) and generate a JSON file with the data. In this case, there will be no requests to your Sanity Content Lake from the browser at all.

However, if you build out this example (or another Next.js site) and start using its Link component or other types of data fetching techniques, then Next.js might want to make requests from the browser. This is why you might want to add Next.js’ URL to your CORS origins settings, or else it won’t work properly.

Browsers come with security that prevents code injection that steals information from your cookies and passes them to third parties. This is called CORS. To allow your CodeSandbox site to get content from your project, you need to add its URL to your project’s CORS origins settings.

👉 First, grab the URL from the preview pane in your Codesandbox; it should look something like this https://RANDOM_LETTERS.csb.app/.

👉 Then head over to the API tab in your project settings at sanity.io/manage. A little bit down the page, you'll find the section named "CORS Origins". Click the button labeled "Add CORS Origin," paste the URL from Codesandbox into the URL field, and hit save (you don’t need to “Allow credentials”). That’s it!

Next steps →

Was this article helpful?