Skip to main content

Cache Clear Tool for Sanity Studio

A custom Sanity Studio tool that allows content editors to clear cache from multiple sources:

  • Next.js Application Cache (in-memory and Redis/Upstash)
  • Vercel Deployment Cache (via Vercel API)
  • Redis/Upstash Cache (via existing cache API endpoints)
note

This tool is installed in the Sanity Studio and provides a UI for content editors to manually clear caches after making content changes.

Quick Setup

1. Generate Cache Authentication Token

The SANITY_STUDIO_CACHE_TOKEN must match the CACHE_AUTH_TOKEN in your Next.js application. Generate a secure token:

Option 1: Using Node.js

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Option 2: Using OpenSSL

openssl rand -hex 32

Option 3: Online Generator

  • Use a secure random string generator (at least 32 characters)
  • Example: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
Security

The token should be at least 32 characters long. Never commit tokens to version control. Use different tokens for development and production environments.

2. Environment Variables

For Sanity Studio (.env file in your Sanity Studio repository):

# Next.js API URL (your production/staging URL)
# IMPORTANT: Don't include trailing slash
SANITY_STUDIO_NEXTJS_URL=http://localhost:3000

# Cache authentication token - MUST match CACHE_AUTH_TOKEN in Next.js
# This is a secret token used to authenticate cache clearing requests
SANITY_STUDIO_CACHE_TOKEN=your-generated-token-here

# Vercel API credentials (optional, only if you want Vercel cache clearing)
VERCEL_TOKEN=your-vercel-token
VERCEL_TEAM_ID=your-team-id
VERCEL_PROJECT_ID=your-project-id

For Next.js Application (.env.local or Vercel environment variables):

# Cache authentication token - MUST match SANITY_STUDIO_CACHE_TOKEN
# This token is used to secure the cache clearing API endpoints
CACHE_AUTH_TOKEN=your-generated-token-here

# Optional: Can also use SANITY_WEBHOOK_SECRET as fallback
SANITY_WEBHOOK_SECRET=your-secret-token-here

# Optional: Specify your Sanity Studio URL for CORS
SANITY_STUDIO_URL=https://your-studio.sanity.studio
NEXT_PUBLIC_SANITY_STUDIO_URL=https://your-studio.sanity.studio

Important:

  • Use the same token value for both SANITY_STUDIO_CACHE_TOKEN (in Sanity Studio) and CACHE_AUTH_TOKEN (in Next.js)
  • Keep this token secret and never commit it to version control
  • Use different tokens for development and production environments
  • The token should be at least 32 characters long for security

3. CORS Configuration

When Sanity Studio (running on localhost:3333) tries to call your Next.js API (running on localhost:3000), you need to configure CORS to allow cross-origin requests.

Your Next.js API routes need to handle CORS. Here's a quick example:

For App Router (Next.js 13+):

// app/api/cache/clear/route.ts
import { NextRequest, NextResponse } from 'next/server'

const ALLOWED_ORIGINS = [
'http://localhost:3333', // Sanity Studio dev
'https://your-studio.sanity.studio', // Sanity Studio production
process.env.SANITY_STUDIO_URL, // From environment variable
].filter(Boolean)

export async function POST(request: NextRequest) {
const origin = request.headers.get('origin')
const isAllowedOrigin = origin && ALLOWED_ORIGINS.includes(origin)

// Verify authentication token
const authHeader = request.headers.get('authorization')
const token = authHeader?.replace('Bearer ', '')
const expectedToken = process.env.CACHE_AUTH_TOKEN

if (!token || token !== expectedToken) {
return NextResponse.json(
{ error: 'Unauthorized' },
{
status: 401,
headers: {
'Access-Control-Allow-Origin': isAllowedOrigin ? origin : '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
}
)
}

// Your cache clearing logic here...

return NextResponse.json(
{ message: 'Cache cleared successfully', deletedCount: 0 },
{
headers: {
'Access-Control-Allow-Origin': isAllowedOrigin ? origin : '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
}
)
}

// Handle preflight requests
export async function OPTIONS(request: NextRequest) {
const origin = request.headers.get('origin')
const allowedOrigins = [
'http://localhost:3333',
'https://your-studio.sanity.studio',
process.env.SANITY_STUDIO_URL,
].filter(Boolean)
const isAllowed = origin && allowedOrigins.includes(origin)

return NextResponse.json(
{},
{
headers: {
'Access-Control-Allow-Origin': isAllowed ? origin : '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400', // 24 hours
},
}
)
}
TODO

Verify that your actual Next.js API route implementation matches this CORS pattern and update this example if needed.

Usage

Once configured, content editors can:

  1. Open Sanity Studio
  2. Click on the "Clear Cache" tool in the toolbar (🗑️ icon)
  3. See three cache options: Next.js, Vercel, and Redis/Upstash
  4. Clear individual caches or all at once
  5. See status feedback for each operation

Common Issues

Double Slash in URL

If you see URLs like http://localhost:3000//api/cache/clear, make sure your SANITY_STUDIO_NEXTJS_URL doesn't end with a slash:

# ✅ Correct
SANITY_STUDIO_NEXTJS_URL=http://localhost:3000

# ❌ Wrong (causes double slash)
SANITY_STUDIO_NEXTJS_URL=http://localhost:3000/

The cache service automatically handles this, but it's better to avoid trailing slashes.

CORS Errors

If you see CORS errors in the browser console:

  1. Make sure your Next.js API route handles OPTIONS requests (preflight)
  2. Check that your Sanity Studio origin is in the allowed origins list
  3. Verify that CORS headers are being set correctly
  4. In development, localhost:3333 should be allowed
  5. In production, your Sanity Studio URL should be in the allowed origins

Token Mismatch

If cache clearing fails with "Unauthorized":

  1. Verify that SANITY_STUDIO_CACHE_TOKEN in Sanity Studio matches CACHE_AUTH_TOKEN in Next.js
  2. Check that both environment variables are set correctly
  3. Restart both Sanity Studio and Next.js after changing environment variables
  4. Check the browser console for warnings about missing tokens

Redirect on Preflight

If you see "Redirect is not allowed for a preflight request":

  1. Check that your API route isn't redirecting (e.g., trailing slash redirect)
  2. Verify your server isn't redirecting HTTP to HTTPS
  3. Ensure your middleware isn't interfering with OPTIONS requests
  4. Make sure the OPTIONS handler returns immediately without redirects

Security Considerations

  • Authentication: All cache clearing endpoints require authentication via Bearer token
  • CORS: Only allows requests from configured Sanity Studio origins
  • Rate Limiting: Consider adding rate limiting to prevent abuse
  • Logging: Log all cache clear operations for audit purposes
  • Permissions: Only allow authorized users to clear cache
warning

Treat cache clearing as a privileged operation. Only authorized content editors should have access to this tool.

Testing

  1. Test each cache type individually
  2. Test clearing all caches at once
  3. Verify that cache is actually cleared by checking the site
  4. Test error handling (invalid tokens, network errors, etc.)
  5. Test CORS by making requests from Sanity Studio

Vercel API Token Setup

To get Vercel API token:

  1. Go to Vercel Dashboard → Settings → Tokens
  2. Create a new token with "Full Account" scope
  3. Add it to your environment variables

To get Project ID:

  1. Go to your project in Vercel
  2. Project ID is in the URL or Settings → General

Additional Features (Optional)

  • Cache Statistics: Display current cache size, hit rate, etc.
  • Selective Clearing: Clear cache for specific document types
  • Scheduled Clearing: Set up automatic cache clearing
  • Cache Warming: Pre-warm cache after clearing
  • History: Log of cache clear operations