Joint session with Vercel: How to build intelligent storefronts (May 15th)

How to get currently logged in user data inside Sanity schema?

16 repliesLast updated: Dec 1, 2025

https://www.sanity.io/docs/migration-cheat-sheet#713ae1bbd4d3 This is still confusing me. I simply need the currently logged in user inside of a schema.

import {useClient, useCurrentUser} from 'sanity'

const GetUserRoles = () => {
    const user = useCurrentUser()
    const {roles} = user
    return roles
}
This doesn't work. Also,
this doesn't look right.
user
!==
currentUser
, must be a typo.Also, this gives an error... it wants export function
MyComponent () {
Is this a typescript shortcut or something?

export function MyComponent {
  const user = useCurrentUser()
  const {id, name, email, profileImage, provider, roles} = currentUser

  return <div>JSX</div>
}
AI Update

You're absolutely right to be confused - there is indeed a typo in the official documentation on that page. Good catch! Let me clear this up:

The Problem in the Docs

The migration cheat sheet shows:

export function MyComponent {  // ❌ Missing parentheses
  const user = useCurrentUser()
  const {id, name, email, profileImage, provider, roles} = currentUser  // ❌ Wrong variable name
  return <div>JSX</div>
}

There are two errors here:

The Correct Way

Here's how to properly use useCurrentUser() in a React component:

import {useCurrentUser} from 'sanity'

export function MyComponent() {  // ✅ Needs parentheses
  const currentUser = useCurrentUser()  // ✅ Can name it whatever you want
  
  // currentUser can be null, so handle that:
  const {id, name, email, profileImage, provider, roles} = currentUser ?? {}
  
  return <div>JSX</div>
}

Key points:

Using Current User in Schema Definitions

Your original code won't work because you cannot use React hooks directly in schema files. Schemas are configuration objects, not React components.

Instead, access currentUser through the context parameter in field-level functions:

export default {
  name: 'myDocument',
  type: 'document',
  fields: [
    {
      name: 'restrictedField',
      type: 'string',
      hidden: ({currentUser}) => {
        // currentUser is available in the context
        return !currentUser?.roles?.some(role => 
          role.name === 'administrator'
        )
      }
    }
  ]
}

The currentUser object in schema contexts has the same shape: {id, name, email, profileImage, provider, roles}.

This is mentioned in the Sanity docs on conditional fields, where currentUser is one of the parameters available to functions like hidden, readOnly, and initialValue.

Show original thread
16 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