First Published Timestamp Function

Official(made by Sanity team)

By Knut Melvær

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.

/studio/schemaTypes/postType.ts

// Add the field to your "post" document type
defineField({
  name: 'firstPublished',
  title: 'First Published',
  type: 'datetime',
  readOnly: true,
})

sanity.blueprint.ts

// Add this to the `resources` array in your blueprint configuraiton
import {defineBlueprint, defineDocumentFunction} from '@sanity/blueprints'

export default defineBlueprint({
  resources: [
    defineDocumentFunction({
      type: 'sanity.function.document',
      name: 'first-published',
      src: './functions/first-published',
      memory: 1,
      timeout: 10,
      event: {
        on: ['publish'],
        filter: "_type == 'post' && !defined(firstPublished)",
        projection: '_id',
      },
    }),
  ],
})

/functions/first-published/index.ts

import {createClient} from '@sanity/client'
import {type DocumentEvent, documentEventHandler, type FunctionContext} from '@sanity/functions'

export const handler = documentEventHandler(
  async ({context, event}: {context: FunctionContext; event: DocumentEvent}) => {
    const client = createClient({
      ...context.clientOptions,
      dataset: 'production',
      apiVersion: 'vX',
      useCdn: false,
    })
    const {data} = event

    try {
      const result = await client.patch(data._id, {
        setIfMissing: {
          firstPublished: new Date().toISOString(),
        },
      })
      console.log('Set firstPublished timestamp for document:', data._id, result)
    } catch (error) {
      console.error('Error setting firstPublished timestamp:', error)
    }
  },
)

functions/first-published/package.json

{
  "name": "first-published",
  "type": "module",
  "main": "index.ts",
  "dependencies": {
    "@sanity/client": "^7.6.0",
    "@sanity/functions": "1.0.2"
  }
}

Content teams need to track when articles were first published for analytics and editorial workflows, but manually setting timestamps is error-prone and often forgotten during the publishing process. This leads to inconsistent data and makes it difficult to analyze content performance over time.

Quick Start

View the complete example and source code

Initialize blueprints if you haven't already: npx sanity blueprints init

Then: npx sanity blueprints add function --example first-published

Then deploy: npx sanity blueprints deploy

How It Works

This function uses Sanity's setIfMissing operation to ensure the timestamp is only set once:

  1. Triggers on the publish event for documents without a firstPublished field
  2. Checks if the field already exists (via the filter)
  3. Sets the current timestamp using setIfMissing
  4. Preserves the original timestamp on all subsequent publishes

The key is the setIfMissing operation, which only sets a value if the field doesn't already exist, preventing accidental overwrites.

Key Benefits

  • Eliminates manual timestamp tracking by automating first-publish detection
  • Ensures data accuracy with automatic timestamp creation
  • Preserves historical data by never overwriting existing timestamps
  • Supports analytics workflows with reliable publication timing data
  • Reduces editorial overhead for content teams

Contributor

Official Recipes by Sanity

Automatically tag blog posts

Featured contribution
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 Automatically tag blog posts

Auto Summary Function

Official(made by Sanity team)

AI-Powered Content Summary from Long Form Content

Kevin Green
Go to Auto Summary Function