How AI is powering better personalization in e-commerce [with Vercel]. Sign up now

Increment likesCount in Sanity dataset via API mutation

7 repliesLast updated: Nov 29, 2025

Hi guys, I am a newbie to the headless CMS world navigating through sanity.io . I need help updating the likesCount in my dataset when user clicks on the like button.

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
Now I have a button in my react component,

&lt;button onClick={addToLikes}&gt;Likes: {selectedService?.likes}&lt;/button&gt;
My addToLikes function is as follows:


const addToLikes = async (selectedService) =&gt; {
  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);
  }
};
I want to make the addLikes function change the value of my dataSet in sanity. so when the user click the button, it should increase the likes by 1. But I am having issues with this. This is how I have my API endpoint set up for mutation, but it is giving me server 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" });
  }
}
What am I doing wrong here?
AI Update

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:

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:

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 thread
7 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.

Related contributions