Increment likesCount in Sanity dataset via API mutation

7 replies
Last updated: Feb 6, 2023
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,

<button onClick={addToLikes}>Likes: {selectedService?.likes}</button>
My addToLikes function is as follows:


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);
  }
};
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:

  1. URL formatting problem: Your apiEndpoint has a malformed URL with <http:// in it
  2. Incorrect mutation structure: The inc operation needs to be inside the patch object correctly
  3. HTTP method: The mutations endpoint uses POST, not PATCH
  4. Patch ID field: Should use id not _id in 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:

  1. Fixed the URL to be properly formatted: https://${projectId}.api.sanity.io/v2023-02-05/data/mutate/${dataset}
  2. Changed _id to id in the patch object (the Mutation API uses id for patch operations)
  3. Changed from axios.patch to axios.post (the mutations endpoint uses POST, not PATCH)
  4. Removed the redundant method: "PATCH" from the config
  5. Removed the unnecessary await result.data line

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
user T
do you think you could help me out with this a little?
Hey User, I’d probably start with using Sanity Client to perform the patch, it should greatly simplify your code!

https://github.com/sanity-io/client#patchupdate-a-document
Thank you , let me look into this.
does this work well with nextjs projects as well?
Sure does!
Perhaps take a look at next-sanity also to register your client globally in your app
https://github.com/sanity-io/next-sanity
And please make sure to use gender neutral language in the community 🙂

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.

Was this answer helpful?