Gathering detailed insights and metrics for @sanity/preview-url-secret
Gathering detailed insights and metrics for @sanity/preview-url-secret
Gathering detailed insights and metrics for @sanity/preview-url-secret
Gathering detailed insights and metrics for @sanity/preview-url-secret
npm install @sanity/preview-url-secret
Typescript
Module System
Min. Node Version
Node Version
NPM Version
visual-editing: v2.15.2
Updated on Jul 11, 2025
svelte-loader: v1.13.43
Updated on Jul 11, 2025
react-loader: v1.11.13
Updated on Jul 11, 2025
presentation-comlink: v1.0.23
Updated on Jul 11, 2025
next-loader: v1.7.0
Updated on Jul 11, 2025
core-loader: v1.8.12
Updated on Jul 11, 2025
TypeScript (93.57%)
JavaScript (1.65%)
Vue (1.6%)
Svelte (1.45%)
Astro (1.31%)
CSS (0.35%)
HTML (0.07%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
51 Stars
3,347 Commits
25 Forks
18 Watchers
68 Branches
50 Contributors
Updated on Jul 15, 2025
Latest Version
2.1.12
Package Id
@sanity/preview-url-secret@2.1.12
Unpacked Size
191.66 kB
Size
41.20 kB
File Count
86
NPM Version
10.9.2
Node Version
22.17.0
Published on
Jul 10, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
1
1npm install @sanity/preview-url-secret @sanity/client
This package is used together with [@sanity/presentation
]:
1// ./sanity.config.ts
2import {defineConfig} from 'sanity'
3import {presentationTool} from 'sanity/presentation'
4
5export default defineConfig({
6 // ... other options
7 plugins: [
8 // ... other plugins
9 presentationTool({
10 previewUrl: {
11 // @TODO change to the URL of the application, or `location.origin` if it's an embedded Studio
12 origin: 'http://localhost:3000',
13 previewMode: {
14 enable: '/api/draft',
15 },
16 },
17 }),
18 ],
19})
[!NOTE] v1 used to require Editor or above to create the secret. v2 lowers the requirement to Contributor.
In order to create an URL Preview Secret, the user needs to have the rights to create draft documents in the schema. By default that means Contributor or above. For Enterprise customers with custom roles, it's possible to grant Viewer roles access to create preview secrets.
In your proiect access settings:
_type == "sanity.previewUrlSecret" && _id in path("drafts.**")
.To grant a user access to Presentation Tool you simply assign them the new "Viewer with Presentation Tool access" role, instead of "Viewer".
In Tools like Presentation, it's possible to share access to a preview link by generating a long lived secret. By default you need to be an Editor or above to enable or disable preview sharing. If preview sharing is enabled, then you need to be Viewer or above to read the secret.
When preview sharing is enabled, Presentation Tool will show a "Share" menu:
By default everyone who's Viewer or above can see a shared preview, once someone who's Editor or above has enabled it for the dataset.
Enterprise customers can restrict this in the following way:
_type != "sanity.previewUrlShareAccess"
.With everything setup correctly, users assigned to this role should see the following when attempting to use the "Share" menu:
If you're still able to see the QR code with the new role assigned, make sure you're not assigned to "Viewer" or other roles that may be granting access to "All documents: Read".
By default anyone who's Editor or above can toggle sharing. If anyone without permission attempts to toggle it they'll see a message like this:
Enterprise customers can customize this in the following way:
_type == "sanity.previewUrlShareAccess"
.Create an API token with viewer rights, and put it in an environment variable named SANITY_API_READ_TOKEN
, then create the following API handler:
1// ./app/api/draft/route.ts 2 3import {client} from '@/sanity/lib/client' 4import {validatePreviewUrl} from '@sanity/preview-url-secret' 5import {draftMode} from 'next/headers' 6import {redirect} from 'next/navigation' 7 8const clientWithToken = client.withConfig({ 9 // Required, otherwise the URL preview secret can't be validated 10 token: process.env.SANITY_API_READ_TOKEN, 11}) 12 13export async function GET(req: Request) { 14 const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, req.url) 15 if (!isValid) { 16 return new Response('Invalid secret', {status: 401}) 17 } 18 19 draftMode().enable() 20 21 redirect(redirectTo) 22}
It's also handy to make a route to disable draft mode, so you have an easy way of disabling it when leaving the Presentation Mode and return to your app:
1// ./app/api/disable-draft/route.ts 2 3import {draftMode} from 'next/headers' 4import {NextRequest, NextResponse} from 'next/server' 5 6export function GET(request: NextRequest) { 7 draftMode().disable() 8 const url = new URL(request.nextUrl) 9 return NextResponse.redirect(new URL('/', url.origin)) 10}
Create an API token with viewer rights, and put it in an environment variable named SANITY_API_READ_TOKEN
, then create the following API handler:
1// ./pages/api/draft.ts 2 3import {client} from '@/sanity/lib/client' 4import {validatePreviewUrl} from '@sanity/preview-url-secret' 5import type {NextApiRequest, NextApiResponse} from 'next' 6 7const clientWithToken = client.withConfig({ 8 // Required, otherwise the URL preview secret can't be validated 9 token: process.env.SANITY_API_READ_TOKEN, 10}) 11 12export default async function handler(req: NextApiRequest, res: NextApiResponse<string | void>) { 13 if (!req.url) { 14 throw new Error('Missing url') 15 } 16 const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, req.url) 17 if (!isValid) { 18 return res.status(401).send('Invalid secret') 19 } 20 // Enable Draft Mode by setting the cookies 21 res.setDraftMode({enable: true}) 22 res.writeHead(307, {Location: redirectTo}) 23 res.end() 24}
It's also handy to make a route to disable draft mode, so you have an easy way of disabling it when leaving the Presentation Mode and return to your app:
1// ./pages/api/disable-draft.ts 2 3import type {NextApiRequest, NextApiResponse} from 'next' 4 5export default function handler(_req: NextApiRequest, res: NextApiResponse<void>): void { 6 // Exit the current user from "Draft Mode". 7 res.setDraftMode({enable: false}) 8 9 // Redirect the user back to the index page. 10 res.writeHead(307, {Location: '/'}) 11 res.end() 12}
Create a session cookie for draft mode, and put it's secret in an environment variable name SANITY_SESSION_SECRET
:
1// ./app/sessions.ts 2 3import {createCookieSessionStorage} from '@remix-run/node' 4 5export const DRAFT_SESSION_NAME = '__draft' 6 7if (!process.env.SANITY_SESSION_SECRET) { 8 throw new Error(`Missing SANITY_SESSION_SECRET in .env`) 9} 10 11const {getSession, commitSession, destroySession} = createCookieSessionStorage({ 12 cookie: { 13 name: DRAFT_SESSION_NAME, 14 secrets: [process.env.SANITY_SESSION_SECRET], 15 sameSite: 'lax', 16 }, 17}) 18 19export {commitSession, destroySession, getSession}
Create an API token with viewer rights, and put it in an environment variable named SANITY_API_READ_TOKEN
, then create the following resource route:
1// ./app/routes/api.draft.ts
2
3import {redirect, type LoaderFunctionArgs} from '@remix-run/node'
4import {validatePreviewUrl} from '@sanity/preview-url-secret'
5import {client} from '~/sanity/client'
6import {commitSession, getSession} from '~/sessions'
7
8export const loader = async ({request}: LoaderFunctionArgs) => {
9 if (!process.env.SANITY_API_READ_TOKEN) {
10 throw new Response('Draft mode missing token!', {status: 401})
11 }
12
13 const clientWithToken = client.withConfig({
14 // Required, otherwise the URL preview secret can't be validated
15 token: process.env.SANITY_API_READ_TOKEN,
16 })
17
18 const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, request.url)
19
20 if (!isValid) {
21 throw new Response('Invalid secret!', {status: 401})
22 }
23
24 const session = await getSession(request.headers.get('Cookie'))
25 await session.set('projectId', client.config().projectId)
26
27 return redirect(redirectTo, {
28 headers: {
29 'Set-Cookie': await commitSession(session),
30 },
31 })
32}
It's also handy to make a resource route to disable draft mode, so you have an easy way of disabling it when leaving the Presentation Mode and return to your app:
1// ./app/routes/api.disable-draft.ts 2 3import {redirect, type LoaderFunctionArgs} from '@remix-run/node' 4import {destroySession, getSession} from '~/sessions' 5 6export const loader = async ({request}: LoaderFunctionArgs) => { 7 const session = await getSession(request.headers.get('Cookie')) 8 9 return redirect('/', { 10 headers: { 11 'Set-Cookie': await destroySession(session), 12 }, 13 }) 14}
Now we can create a utility function that helps us get the draft mode from the session cookie in loaders:
1// ./app/sanity/get-draft-mode.server.ts 2 3import {client} from '~/sanity/client' 4import {getSession} from '~/sessions' 5 6export async function getDraftMode(request: Request) { 7 const draftSession = await getSession(request.headers.get('Cookie')) 8 const draft = draftSession.get('projectId') === client.config().projectId 9 10 if (draft && !process.env.SANITY_API_READ_TOKEN) { 11 throw new Error( 12 `Cannot activate draft mode without a 'SANITY_API_READ_TOKEN' token in your environment variables.`, 13 ) 14 } 15 16 return draft 17}
You can inspect the URL origin of the Studio that initiated the preview on the studioOrigin
property of validatePreviewUrl
:
1const {isValid, redirectTo = '/', studioOrigin} = await validatePreviewUrl(clientWithToken, req.url) 2if (studioOrigin === 'http://localhost:3333') { 3 console.log('This preview was initiated from the local development Studio') 4}
You don't have to check isValid
before using it, as it'll be undefined
if the preview URL secret failed validation. It's also undefined
if the way the secret were created didn't provide an origin.
You can view the generated url secrets that are in your dataset by adding the debug plugin to your sanity.config.ts
:
1import {debugSecrets} from '@sanity/preview-url-secret/sanity-plugin-debug-secrets'
2import {defineConfig} from 'sanity'
3
4export default defineConfig({
5 // ... other options
6 plugins: [
7 // Makes the url secrets visible in the Sanity Studio like any other documents defined in your schema
8 debugSecrets(),
9 ],
10})
No vulnerabilities found.
No security vulnerabilities found.