
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeI can see the issue! You're on the right track, but there are a few problems with your API endpoint code. Let me help you fix this.
The main issues are:
apiEndpoint has a malformed URL with <http:// in itinc operation needs to be inside the patch object correctlyid not _id in patch operationsHere's your corrected /pages/api/updateLikes.js:
import axios from "axios";
export default async function handler(request, response) {
try {
const data = JSON.parse(request.body);
const mutations = {
mutations: [
{
patch: {
id: data.id, // Use 'id' not '_id' in patch operations
inc: { likes: 1 }
}
}
]
};
const apiEndpoint = `https://${process.env.NEXT_PUBLIC_SANITY_PROJECT_ID}.api.sanity.io/v2023-02-05/data/mutate/${process.env.NEXT_PUBLIC_SANITY_DATASET}`;
const result = await axios.post(apiEndpoint, mutations, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.SANITY_API_TOKEN}`
}
});
response.status(200).json({ message: "likes increased", data: result.data });
} catch (error) {
console.error(error.response?.data || error);
response.status(500).json({
message: "Server error",
error: error.response?.data || error.message
});
}
}Key changes:
https://${projectId}.api.sanity.io/v2023-02-05/data/mutate/${dataset}_id to id in the patch object (the Mutation API uses id for patch operations)axios.patch to axios.post (the mutations endpoint uses POST, not PATCH)method: "PATCH" from the configawait result.data lineImportant: Token Permissions
Make sure your SANITY_API_TOKEN has write permissions. You can create one in your Sanity project dashboard at manage.sanity.io → Your Project → API → Tokens. Create a token with "Editor" or "Administrator" permissions.
Security Note: Never expose your write token in NEXT_PUBLIC_ variables - keep SANITY_API_TOKEN as a server-only environment variable (without the NEXT_PUBLIC_ prefix), which you're already doing correctly!
Your client-side code looks fine, though you might want to update the component state after the mutation succeeds to reflect the new likes count without requiring a page refresh.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store