examples/functions/auto-redirect/README.md
When a slug changes people may still try to access content from using the old slug. We also want the SEO ranking to be passed to the new URL. Content creators spend time manually creating redirects which could be prone to error.
This Sanity function automatically creates a redirect document when the value of the slug field is updated and stores it as a permanent redirect.
This function is built to be compatible with the schema for Next.js as described in Managing redirects with Sanity guide.
// schemas/redirect.ts
import {defineType, defineField, type Rule, type Slug} from 'sanity'
// Shared validation for our redirect slugs
const slugValidator = (rule: Rule) =>
rule.required().custom((value: Slug) => {
if (!value || !value.current) return "Can't be blank"
if (!value.current.startsWith('/')) {
return 'The path must start with a /'
}
return true
})
export const redirectType = defineType({
name: 'redirect',
title: 'Redirect',
type: 'document',
description: 'Redirect for next.config.js',
fields: [
defineField({
name: 'source',
type: 'slug',
validation: (rule: Rule) => slugValidator(rule),
}),
defineField({
name: 'destination',
type: 'slug',
validation: (rule: Rule) => slugValidator(rule),
}),
defineField({
name: 'permanent',
type: 'boolean',
}),
],
// null / false makes it temporary (307)
initialValue: {
permanent: true,
},
})
Important: Run these commands from the root of your project (not inside the studio/ folder).
Run this if you haven't initialized blueprints:
npx sanity blueprints init
You'll be prompted to select your organization and Sanity studio.
Then run:
npx sanity blueprints add function --example auto-redirect
// sanity.blueprint.ts
import {defineBlueprint, defineDocumentFunction} from '@sanity/blueprints'
export default defineBlueprint({
resources: [
defineDocumentFunction({
name: 'auto-redirect',
src: './functions/auto-redirect',
memory: 2,
timeout: 30,
event: {
on: ['update'],
filter: 'delta::changedAny(slug.current)',
projection: '{"beforeSlug": before().slug.current, "slug": after().slug.current}',
},
}),
],
})
Install dependencies
Install dependencies in the project root:
npm install
Make sure you have a schema deployed
From the studio folder, run:
# In the studio/ folder (adjust path for template structure)
npx sanity schema deploy
You can test the auto-redirect function locally using the Sanity CLI before deploying it to production.
As the filter and projection are using advanced GROQ functions they currently need to be commented out when testing locally
As this function uses the before() and after() functions you need to test the function with the included document.json or by using the development server
To test using the cli
# Back to project root for function testing
npx sanity functions test auto-redirect --file functions/auto-redirect/document.json --with-user-token
Start the development server for interactive testing:
npx sanity functions dev
This opens an interactive playground where you can test functions with custom data
To see detailed logs during testing, modify the function temporarily to add logging:
// Add this to your function for debugging
console.log('Event data:', JSON.stringify(event.data, null, 2))
console.log('Result:', result)
redirect document type containing:
source field of type slugdestination field of type slugpermanent field of type booleanslug field of type slugWhen a content editor publishes a document with a changed slug field, the function automatically:
This results in SEO rankings being passed on and old links still working.
Modify the blueprint filter to target specific content types:
filter: "_type == 'article' && delta::changedAny(slug.current)"