Skip to content
gilltrish.dev

Preview your Sanity drafts in Astro (without leaking them)

Getting comfortable6 min read

The 30-second version

Drafts in Sanity are private, so a public static site can’t see them. Make a read-only (Viewer) token, keep it in a gitignored .env.preview file, and switch the Sanity client to the drafts perspective only when the dev server runs in preview mode. A banner makes the preview impossible to mistake for the live site, and builds never read drafts, even if the token is set.

On this page

My microanimations post has moving demos, pause buttons, code blocks and callouts. The Sanity Studio is great for checking the words, but it can’t show me whether a demo sits nicely next to the text, or whether a code block runs off the edge on a phone.

So I asked a simple question: can I see my post exactly as readers will, before I publish it? The answer was yes, with one command and one secret key.

By the end of this post, npm run dev:preview, will show your unpublished drafts on your own computer with the real layout, while the live site stays exactly as it is.

Why can’t the site see my drafts?

Sanity keeps two copies of a post while you work on it: the published one everyone can see, and a draft only you can see. Think of the draft as a note in your diary and the published post as a letter you’ve posted.

This site’s Sanity data is public, so the website can read published posts without a password. Drafts are private. To read them, the site needs a key: an API token.

How draft preview works

  1. Edit in the StudioSanity saves a draft
  2. Run dev:previewUses your read-only key
  3. Ask for draftsNewest version of everything
  4. LocalhostReal layout, with a banner

Step 1:Make a read-only token

  • Go to sanity.io/manage and open your project.
  • Open API, then Tokens, then Add API token.
  • Give it a name you’ll recognise later, like “Local draft preview”.
  • Pick Viewer. It can read everything, including drafts, but can’t change anything.
  • Copy the token now. Sanity only shows it once.

Treat it like a password

Anyone with this token can read your drafts. It goes in one local file and nowhere else: not in Git, not in Cloudflare, not in a screenshot. If it leaks, delete it on the same Tokens page and make a new one.

Step 2:Put it in a file Git ignores

Astro has “modes”. Running it with --mode preview makes it load a file called .env.preview on top of the usual settings. Create it in the web folder:

web/.env.preview· .env
SANITY_API_READ_TOKEN=paste-your-token-here

Check that Git ignores it. This project’s .gitignore has .env.*, which covers it. You can ask Git directly:

PowerShell

    
        
        
        git check-ignore -v web/.env.preview
      
        
        
        .gitignore:15:.env.*    web/.env.preview
      
  

What I’d tell past me

If that prints nothing, the file isn’t ignored. Fix .gitignore before you do anything else.

Then add a script to web/package.json, so you don’t have to remember the flag:

web/package.json· JSON
"scripts": {
  "dev:preview": "astro dev --mode preview"
}

Step 3:Tell Astro the token is a secret

This site declares its settings with astro:env, which checks them when the site starts. Marking the token as secret and server means it’s only available to code that runs on your computer, never sent to the browser.

astro.config.mjs· JavaScript
env: {
  schema: {
    SANITY_API_READ_TOKEN: envField.string({context: 'server', access: 'secret', optional: true}),
  },
},

Step 4:Ask Sanity for drafts, but only in preview

Sanity calls the different views of your content “perspectives”. published shows only what’s live. drafts shows the newest version of everything: your draft where one exists, otherwise the published post.

src/sanity/client.ts· TypeScript
import {createClient} from '@sanity/client'
import {PUBLIC_SANITY_DATASET, PUBLIC_SANITY_PROJECT_ID} from 'astro:env/client'
import {SANITY_API_READ_TOKEN} from 'astro:env/server'

/**
 * `npm run dev:preview` shows drafts on localhost. Both checks have to pass: it's the dev
 * server (never a build, so drafts can't end up in dist/) and the `preview` mode. Anywhere
 * else the token is ignored even if it's set.
 */
export const isDraftPreview = import.meta.env.DEV && import.meta.env.MODE === 'preview'

if (isDraftPreview && !SANITY_API_READ_TOKEN) {
  throw new Error(
    'Draft preview needs SANITY_API_READ_TOKEN in web/.env.preview (a Viewer token from sanity.io/manage → API → Tokens).',
  )
}

/**
 * Every query runs at build time, so there's no reason to use the CDN:
 * the live API returns content the moment it's published, and the build
 * only makes one request per page anyway. The dataset is public, so no token,
 * except in draft preview: drafts are private, so reading them needs one.
 */
export const sanityClient = createClient({
  projectId: PUBLIC_SANITY_PROJECT_ID,
  dataset: PUBLIC_SANITY_DATASET,
  apiVersion: '2026-10-01',
  useCdn: false,
  // `drafts` = the newest version of everything: a draft where one exists, otherwise the published doc.
  perspective: isDraftPreview ? 'drafts' : 'published',
  token: isDraftPreview ? SANITY_API_READ_TOKEN : undefined,
})

Two locks on the door

isDraftPreview needs both import.meta.env.DEV (it’s the dev server, not a build) and the preview mode. So even if the token somehow ended up in a build, the build would still only read published posts. Drafts can’t end up on the live site by accident.

If you forget the token, the site stops with a message saying exactly what’s missing, instead of quietly showing published content and leaving you wondering why your changes aren’t there.

Step 5:Add a banner you can’t miss

A preview that looks exactly like the live site is a trap. One yellow line at the top of every page fixes that:

src/layouts/BaseLayout.astro· Astro
{isDraftPreview && (
  <p class="bg-highlight px-4 py-2 text-center text-sm font-bold text-on-highlight">
    Draft preview: you’re seeing unpublished changes. This isn’t the live site.
  </p>
)}

Step 6:Reload when you type

This site already had a small helper that reloads the dev server when something is published. In preview mode it now listens to drafts too, using the same token.

Drafts change on every keystroke, so it waits for a 1.5-second pause in typing before reloading. Otherwise the page would reload after every letter.

integrations/sanity-dev-refresh.ts· TypeScript
const drafts = server.config.mode === 'preview'

client
  .listen(drafts ? '*' : '*[!(_id in path("drafts.**"))]', {}, {events: ['mutation']})
  .subscribe({next: refresh})

Step 7:Try it

PowerShell

    
        
        
        npm run dev:preview
      
        
        
        Open the address it prints, then go to your draft post
      
  

You should see the yellow banner and your draft post. Change a word in the Studio, stop typing, and the page reloads with your change.

What could go wrong

  • Your draft isn’t in the list. Check its publish date. This site hides posts dated in the future, and the preview follows the same rule.
  • It looks right in preview but not live. Things the post links to need publishing too. A new tag that’s still a draft shows in preview, but disappears from the live post until you publish the tag.
  • “Draft preview needs SANITY_API_READ_TOKEN”. The file is missing, misnamed or in the wrong folder. It has to be web/.env.preview.
  • Only one dev server at a time. Astro 7 runs one dev server per project, so stop npm run dev before starting the preview.

Fine for one editor, not for a client

This works because I’m the only person editing this site, and I’m happy in a terminal. A client who only edits content won’t have the code, the token or npm, so they need a preview they can open from the Studio:

  • A site that can render drafts. The pages have to be built when someone asks for them, not ahead of time. Next.js sites can do this out of the box. A fully static site like this one would need a few server-rendered pages added.
  • A button in the Studio. Sanity’s Presentation tool shows that preview next to the editor, so they see the real page update as they type.
  • The token stays on the server. It lives in the preview site’s hosting settings, never in the browser, and the public site still only reads published posts.

What I’d tell past me

Don’t wait until a post is finished to preview it. Layout problems are easier to fix while the post is still taking shape, and seeing the real page often changes what I write.