如何在Sanity CMS中创建可执行自定义服务端代码的API端点?
Got it, let's break down how to set up custom API endpoints in Sanity that run server-side code—just like you’re used to with Next.js’s /pages/api routes. This is perfect for integrating with third-party systems, so here’s a step-by-step guide tailored to your needs:
1. Use Sanity's Built-in Routes (v3) or @sanity/server (v2)
Sanity’s approach varies slightly between versions, so pick the method that matches your project:
For Sanity v3 (Modern Recommended Approach)
Sanity v3 lets you define custom routes directly in your sanity.config.js file using the routes property in your config. No extra packages needed!
Here’s a sample implementation with GET and POST endpoints:
import {defineConfig} from 'sanity' import {structureTool} from 'sanity/structure' import {createClient} from '@sanity/client' // Initialize a Sanity client if you need to interact with your dataset const sanityClient = createClient({ projectId: 'your-project-id', dataset: 'production', token: process.env.SANITY_API_TOKEN, // Optional, for read/write access useCdn: false }) export default defineConfig({ name: 'default', title: 'My Sanity Project', projectId: 'your-project-id', dataset: 'production', plugins: [structureTool()], // Define your custom API routes here routes: [ // GET endpoint example { method: 'GET', path: '/api/my-endpoint', handler: async (req, res) => { // Your server-side logic goes here // Example: Fetch data from a third-party API const thirdPartyResponse = await fetch('https://api.thirdparty.com/data') const thirdPartyData = await thirdPartyResponse.json() // Or fetch data from your Sanity dataset const sanityPosts = await sanityClient.fetch('*[_type == "post"]') // Send a JSON response back res.status(200).json({ message: 'Success!', thirdPartyData, sanityPosts }) } }, // POST endpoint example { method: 'POST', path: '/api/my-endpoint', handler: async (req, res) => { // Parse the incoming request body const requestBody = await req.json() // Example: Create a new document in Sanity const newDocument = await sanityClient.create({ _type: 'feedback', message: requestBody.message, submittedAt: new Date().toISOString() }) res.status(201).json({ message: 'Feedback created successfully', document: newDocument }) } } ] })
Once deployed, you can access these endpoints at https://<your-sanity-project>.sanity.studio/api/my-endpoint (or your custom domain if you’ve configured one). For local development, run sanity dev and use http://localhost:3333/api/my-endpoint.
For Sanity v2
If you’re still on v2, you’ll need to use the @sanity/server package to set up custom endpoints:
- First, install the package:
npm install @sanity/server --save
- Create a
server.jsfile in your project root:
const sanityServer = require('@sanity/server') const {createClient} = require('@sanity/client') // Initialize Sanity client const sanityClient = createClient({ projectId: 'your-project-id', dataset: 'production', token: process.env.SANITY_API_TOKEN, useCdn: false }) // Set up the custom server const server = sanityServer({ projectId: 'your-project-id', dataset: 'production', routes: [ { method: 'GET', path: '/api/my-endpoint', handler: async (req, res) => { // Server-side logic here const products = await sanityClient.fetch('*[_type == "product"]') res.status(200).json({products}) } } ] }) // Start the server for local development server.listen(3333, () => { console.log('Custom Sanity server running at http://localhost:3333') })
You can host this server separately (e.g., on Vercel, Heroku) or integrate it into your deployment pipeline. The endpoint will be available at your server’s domain plus /api/my-endpoint.
2. Add Authentication (If Required)
If you need to restrict access to your endpoints (e.g., only allow trusted third-party systems), add an auth check in your handler:
handler: async (req, res) => { // Check for a secret API key in request headers const apiKey = req.headers['x-api-key'] if (apiKey !== process.env.MY_CUSTOM_SECRET_KEY) { return res.status(401).json({error: 'Unauthorized access'}) } // Proceed with your server-side logic // ... }
Store your secret keys in Sanity’s environment variables (via the Sanity dashboard or a .env file for local dev).
3. Testing Endpoints Locally
- For v3: Run
sanity devand send requests tohttp://localhost:3333/api/my-endpointusing tools like Postman or curl. - For v2: Run
node server.jsand test the local endpoint the same way.
内容的提问来源于stack exchange,提问作者owenmelbz

