'How to create a new user along with their profile images in Sanity?

Hi I am a beginner to Sanity and I am working on a personal project. All I want to know is how do I add a user along with his profile Image selected as a file from his device to the Sanity Database. I want the details whatever they entered in this form to be saved in the backend. I am using Next.js.


   <div className="flex h-screen flex-col items-center justify-center bg-[#171821]">
    <div className="m-6">
        <form>
          <input
              aria-label="Enter your email address"
              type="text"
              placeholder="User Name"
              className="text-gray-base mr-3 mb-2 h-2 w-full roundedpy-5 px-4 text-sm bg-black text-white"/>
      
<button type="submit" className="mt-5 w-full bg-green-400 p-2">
            Add User
          </button>
        </form>
      </div>
    </div>

Here is my simple sanity schema


  export default {
    name: 'user',
    title: 'User',
    type: 'document',
    fields: [
        {
            name: 'user_name',
            title: 'User Name',
            type: 'string',
        },
        {
            name: 'profile_image',
            title: 'Profile Image',
            type: 'image',
        },
    ]
}



Solution 1:[1]

You can use the JavaScript client to perform mutations like this. If each user is aligned with a document, you might look at the create() method. Be sure you consider the security of your token, as you'll need to use a write token and that will provide full CRUD access to your entire project's content.

Solution 2:[2]

Initialize the sanity client:

import SanityClient from '@sanity/client'

export const client = sanityClient({
  projectId: process.env.SANITY_PROJECT_ID,
  dataset: 'production',
  apiVersion: 'v1',
  token: process.env.SANITY_TOKEN,
  useCdn: false,
})

write an api function in pages/api/createUser

import { client } from '../../lib/sanity'

const createUserOnSanity = async (req, res) => {
  try {
    const userDoc = {
      _type: 'users',
      name: req.body.name,
      profileImage: req.body.profileImage,
      ...
    }

    await client.createIfNotExists(userDoc)

    res.status(200).send({ message: 'success' })
  } catch (error) {
    res.status(500).send({ message: 'error', data: error.message })
  }
}

export default createUserOnSanity

Then in your component, make a post request to this api

try {
      await fetch(`/api/createUser`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: name,
          // uploading file from computer needs extra work
          // I just pass url
          profileImage: event.target.url.value,
        }),
      })
    } catch (error) {
      console.error(error)
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Geoff Ball
Solution 2 Yilmaz