Initial value template with current user

By Knut Melvær

Use data for the current logged in user as initial values in a new document

initialValueTemplates.js

// initialValueTemplates.js

import T from '@sanity/base/initial-value-template-builder'
import userStore from 'part:@sanity/base/user'

export default {
  ...T.defaults,
  T.template({
    id: 'newsStory',
    title: 'News story',
    schemaType: 'newsStory',
    value: async () => {
      const {name, id} = await userStore.getUser('me')
      return {
        author: {
          name,
          id,
          _type: 'author'
        },
      }
    }
  })
}

/*
Shape of the user object from userStore.getUser('me'):
{
  "id": "pCuO6i54C",
  "projectId": "3do82whm",
  "displayName": "Your name",
  "familyName": "Your family name",
  "givenName": "Your given name",
  "middleName": "Your middle name",
  "imageUrl": "<your-avatar-image>",
  "createdAt": "2018-04-02T14:21:46.688Z",
  "updatedAt": "2020-12-30T08:21:25.286Z",
  "isCurrentUser": true
}
*/

author.js

export default {
  name: 'author',
  type: 'object',
  title: 'Author',
  fields: [
    {
      name: 'name',
      type: 'string',
      title: 'Full name'
    },
    {
      name: 'id',
      type: 'string',
      title: 'User ID',
      readOnly: true,
      description: `This author's user ID. Used for workflow scripts and similar.`
    }
  ]
}

This example shows how to use the userStore to fetch the logged-in user, and use the data from the user object to populate an author field using the Initial Value Templates API.

Contributor

Other schemas by the contributor

First Published Timestamp Function

Official(made by Sanity team)

Automatically track when content was first published with a timestamp that sets once and never overwrites, providing reliable publication history for analytics and editorial workflows.

Knut Melvær
Go to First Published Timestamp Function

Auto-Tag Function

Official(made by Sanity team)

AI-powered automatic tagging for Sanity blog posts that analyzes content to generate 3 relevant tags, maintaining consistency by reusing existing tags from your content library.

Go to Auto-Tag Function