CoursesIntegrated Visual Editing with Next.jsToken handling and security
Track
Work-ready Next.js

Integrated Visual Editing with Next.js

Lesson
2

Token handling and security

Log in to watch a video walkthrough of this lesson
Log in
Video thumbnail
To access draft content your application will need to be authenticated with a token. Learn how to do this securely.
Log in to mark your progress for each Lesson and Task

In a public dataset, documents are kept private in the Content Lake when they have a period (.) in the _id attribute. For example, draft document IDs begin with a drafts. prefix.

Authentication will also be required to use the previewDrafts "perspective," a method of performing a GROQ query that returns the latest draft version of a document instead of an already-published document.

Learn more about Perspectives for Content Lake in the documentation

To view draft content, requests to the Content Lake require authentication.

On the client side, the same credentials that allow authors to log in to Sanity Studio will handle this. On the server side, an API token will be required.

Learn more about Authentication in the documentation

Access tokens can be created from Manage or the API.

You can access Manage for your project either from the menu at the top right of your Studio:

Or you can automatically open your browser to the Manage page of your project from the command line:

npx sanity@latest manage
In Manage, go to the "API" tab and create a token with "Viewer" perimssions
Update your .env.local file to include the token
.env.local
NEXT_PUBLIC_SANITY_PROJECT_ID="your-project-id"
NEXT_PUBLIC_SANITY_DATASET="your-dataset-name"
SANITY_REVALIDATE_SECRET="your-secret"
# 👇 add this line
SANITY_API_READ_TOKEN="your-new-token"
It is your responsibility to secure this token. Unencrypted access could allow a user to read any document from any dataset in your project. The way it is implemented in this course should never lead to it being included in your code bundle.

You may need to restart your development environment to make the token available. The file below will throw an error if the token is not found in your environment variables.

Create a new file to store, protect, and export this token
src/sanity/lib/token.ts
export const token = process.env.SANITY_API_READ_TOKEN
if (!token) {
throw new Error('Missing SANITY_API_READ_TOKEN')
}

Now the token can be exported from a reliable location. In the next lesson you'll add it to the defineLive function.

You have 3 uncompleted tasks in this lesson
0 of 3