Conditionally show Desk sidebar items based on current user role
useCurrentUserfrom inside
sanity.config.tsI get a nasty warning and I realize that it is because I’m using a hook and it is not inside a React component. My question is where would be the best place to make this call, or is there another “non-hook” way to go about getting the currently logged in user? Thanks for any pointers.
You're on the right track! You can't use React hooks like useCurrentUser in sanity.config.ts because it's not a React component. The solution is to use the context parameter that Sanity provides in the configuration callback functions.
In your sanity.config.ts, both the tools and plugins configuration options accept a callback function that receives a context object as the second parameter. This context object includes a currentUser property that you can use to conditionally show/hide tools based on user attributes.
Here's how to do it:
// sanity.config.ts
import { defineConfig } from 'sanity'
import { structureTool } from 'sanity/structure'
import { myCustomTool } from './myCustomTool'
export default defineConfig({
// ... other config
tools: (prev, context) => {
const { currentUser } = context
// Filter tools based on user role
const filteredTools = prev.filter(tool => {
// Hide settings for non-admins
if (tool.name === 'settings') {
return currentUser?.roles.some(role => role.name === 'administrator')
}
return true
})
// Or add tools conditionally based on email
if (currentUser?.email === 'special@example.com') {
filteredTools.push(myCustomTool)
}
return filteredTools
},
plugins: [
structureTool({
structure: (S, context) => {
// You also have access to currentUser here
const { currentUser } = context
// Customize your desk structure based on user
// ...
}
})
]
})The Studio configuration documentation confirms that the context object includes both currentUser and getClient. The currentUser object contains properties like:
email- The user's email addressroles- An array of role objects withnameandtitlepropertiesid- The user's unique identifier
For more complex role-based customizations, you might also want to check out the Studio customizations course on Sanity Learn which covers exactly this use case.
Pro tip: If you're doing this check in multiple places, consider creating a helper function like userHasRole(currentUser, 'administrator') to keep your code DRY and make your configuration more readable.
Show original thread4 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.