Increment likesCount in Sanity dataset via API mutation
I was able to use sanity to manually import some data into my sanity dataset and fetch it from an endpoint that I created in my nextjs App. now I need your help to mutate a number property.
this is a sample of one of my documents
likes:120
price:50
rating:4.5
seller:{…} 2 properties
_ref:3a45f32e-e6b3-4eef-984a-515a595b25ad
_type:reference
serviceImageUrl:<https://cdn.discordapp.com/attachments/990816819654852648/1063634376849629194/needmadnes33_two_people_sitting_on_the_couch_and_watching_tv_tv_1ff1b756-feb1-410a-97a3-97055562b522.png>
title:Accompaniment for a TV show marathon
visits:180<button onClick={addToLikes}>Likes: {selectedService?.likes}</button>const addToLikes = async (selectedService) => {
console.log("addToLikes triggered");
try {
const data = { id: selectedService.id };
const result = await axios.patch("/api/updateLikes", data);
console.log(result.data);
} catch (error) {
console.error(error);
}
};/pages/api/updateLikes.js file below:
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,
inc: { likes: 1 },
},
},
],
};
const apiEndpoint = `https://${process.env.NEXT_PUBLIC_SANITY_PROJECT_ID}.<http://api.sanity.io/v2023-02-05/data/mutate/${process.env.NEXT_PUBLIC_SANITY_DATASET}`;|api.sanity.io/v2023-02-05/data/mutate/${process.env.NEXT_PUBLIC_SANITY_DATASET}`;>
const result = await axios.patch(apiEndpoint, mutations, {
headers: {
"content-type": "application/json;charset=utf-8",
Authorization: `Bearer ${process.env.SANITY_API_TOKEN}`,
},
method: "PATCH",
});
await result.data;
response.status(200).json({ message: "likes increased" });
} catch (error) {
console.error(error);
response.status(500).json({ message: "Server error" });
}
}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 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
Was this answer helpful?
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.