Increment likesCount in Sanity dataset via API mutation
I 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:
- URL formatting problem: Your
apiEndpointhas a malformed URL with<http://in it - Incorrect mutation structure: The
incoperation needs to be inside thepatchobject correctly - HTTP method: The mutations endpoint uses POST, not PATCH
- Patch ID field: Should use
idnot_idin patch operations
Here'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:
- Fixed the URL to be properly formatted:
https://${projectId}.api.sanity.io/v2023-02-05/data/mutate/${dataset} - Changed
_idtoidin the patch object (the Mutation API usesidfor patch operations) - Changed from
axios.patchtoaxios.post(the mutations endpoint uses POST, not PATCH) - Removed the redundant
method: "PATCH"from the config - Removed the unnecessary
await result.dataline
Important: 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.
Show original thread7 replies
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.