Revalidation

Revalidation is necessary for JAMStack Projects. It tells the server when the content is updated in the CMS. So users will see the latest content without you re-deploying the website each time.

This is a general instruction on integrating revalidation with Sanity CMS and Next.js. Make sure you make the necessary changes according to the features and frameworks.

Sanity CMS provides GROQ-powered Webhook feature which will be used to trigger our revalidation in our Next.js Project.

Step 1: Creating Webhook #

  1. Go to the API section of your Sanity project on sanity.io/manage
  2. Click the "Create webhook" option
  3. Set the Name & Description
  4. Set the URL to https://YOUR_SITE_URL.com/api/revalidate
  5. Choose Dataset to "production" or choose the one you prefer.
  6. Set the following options as shown below.
  7. Trigger on: "Create", "Update", and "Delete"
  8. Set Filter: _type == "post" (or your custom post type name)
  9. Projection: Leave empty
  10. Status: Keep it enabled
  11. HTTP method: POST
  12. HTTP Headers: Leave empty
  13. API version: v2021-03-25
  14. Include drafts: No
  15. Secret: Random value (Copy it as we need this for next step)
  16. Now, Save the configuration and create a webhook

You can also run npx sanity hook create in your project terminal to create a new webhook in sanity.

Step 2: Adding Secret #

Now, copy the secret you created earlier and add it to your `.env.local` file as well as vercel or production env using the name: SANITY_REVALIDATE_SECRET

To add the secret to vercel using the terminal, use the following command.

npx vercel env add SANITY_REVALIDATE_SECRET

Step: 3 Update Revalidation Logic #

To change which pages to update, open /api/revalidate.ts file and change the logic on what files to update. By default, it looks for the current /post/[slug] path and home page and updates it when a change happens.

You can add or update the pages and the logic as needed for your project.

Step 4: Redeploy Project #

Once everything looks good, you can re-deploy the project to activate the Revalidation API using the Groq powered Webhook.

Use the following command for vercel deploy from terminal

npx vercel --prod