How to get the currently logged in user inside a Sanity schema
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:
- Missing
()afterMyComponent- it needs to be a proper function declaration - Destructuring from
currentUserwhen the variable is actually nameduser
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:
export function MyComponent()needs parentheses - this is standard JavaScript function syntax, not a TypeScript shortcut- The hook returns a user object that you can name anything (
user,currentUser, etc.) useCurrentUser()returnsCurrentUser | null, so use optional chaining (?.) or nullish coalescing (??) to handle the null case
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.
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.