How to Execute Custom Code via an API Endpoint with Next.JS
Unfortunately, Sanity doesn't currently provide a built-in way to create custom HTTP API endpoints directly within the Sanity platform (like Next.js's /pages/api/my-endpoint.js).
Here's what's actually available and what you'll need to do:
The Current Reality
Sanity Functions are event-driven, not HTTP endpoints. They're triggered by document changes (create, update, delete events) and run automatically in response to those events. You can't call them directly via a URL from Studio components.
Webhooks work in the opposite direction - they send HTTP requests OUT to external services when content changes occur. They don't receive incoming HTTP calls.
Your Best Options
For a "send an email" component in Studio that needs server-side execution, you'll need to:
1. Use Next.js API Routes (Recommended)
Keep your Next.js API routes as the backend for Studio actions:
// In your Studio component
const handleSendEmail = async () => {
await fetch('https://your-nextjs-app.com/api/send-email', {
method: 'POST',
body: JSON.stringify({to, subject, body})
})
}This is actually a solid pattern - your Next.js app provides the API infrastructure while Studio provides the UI.
2. Deploy Separate Serverless Functions
Use services like:
- Vercel Functions
- Netlify Functions
- AWS Lambda
- Cloudflare Workers
Then call those endpoints from your Studio component.
3. Use Document Actions with Sanity Functions
If your use case fits an event-driven model (e.g., "send email when document is published"), you could:
- Create a custom document action in Studio
- Have it trigger a document change that Sanity Functions listens for
- The Function executes your email logic
This is more indirect but keeps everything within Sanity's infrastructure.
Why This Limitation Exists
Sanity is positioning itself as a "Content Operating System" where Sanity Functions handle content lifecycle automation, while external services handle general-purpose HTTP endpoints. The platform is optimized for content operations rather than general API hosting.
For your specific use case, sticking with Next.js API routes is perfectly valid and actually quite common in the Sanity community!
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.