UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

197 lines (148 loc) • 7.12 kB
# Draft mode > Let an editor see unpublished content on a page that is prerendered, kept or cached at a CDN, without a rebuild and without anyone else seeing it. A prerendered page, a page that exports `revalidate` and a partially prerendered shell all serve a copy made earlier, for everyone. An editor who just saved a draft wants to see it on the real page. Draft mode does that for one visitor: while it is on, their requests skip every stored copy and render the page now, and nobody else is affected. Turn it on from a server action: ```ts title="src/app/posts/actions.ts" 'use server' import { draftMode } from '@rsc-kit/core/draft' import { redirect } from '@rsc-kit/core/redirect' export async function preview(slug: string) { // Check the visitor may see drafts first: this is a switch, not a guard. await (await draftMode()).enable() redirect(`/posts/${slug}`) } export async function stopPreviewing() { await (await draftMode()).disable() } ``` And read it in the page: ```tsx title="src/app/posts/[slug]/page.tsx" import { draftMode } from '@rsc-kit/core/draft' export const revalidate = 300 export default async function Post({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params const { isEnabled } = await draftMode() const post = isEnabled ? await findLatestPost(slug) : await findPublishedPost(slug) return ( <article> {isEnabled && <p>Draft preview</p>} <h1>{post.title}</h1> </article> ) } ``` Everyone else still gets the kept copy. The editor gets a fresh render on every request until they call `disable()`, or until the cookie expires an hour later. ## Turning it on and off `enable()` and `disable()` set a cookie, so call them anywhere a cookie can still be set: a server action, a `route.ts`, or a middleware. A page cannot call them, because its headers have already been sent. Called from an action, the page the action came from is rendered again in the same answer, in its new mode. The pages the tab prefetched or kept in its history are dropped too, so the editor never sees a published copy after turning draft mode on, and never sees a draft after turning it off. A link from somewhere else, such as a CMS that opens your site in a new tab, can go to a route handler: ```ts title="src/app/api/preview/route.ts" import { draftMode } from '@rsc-kit/core/draft' export async function GET(request: Request) { const url = new URL(request.url) if (url.searchParams.get('token') !== process.env.PREVIEW_TOKEN) { return new Response('Not allowed', { status: 403 }) } await (await draftMode()).enable() return Response.redirect(new URL(`/posts/${url.searchParams.get('slug')}`, url), 303) } ``` `enable({ maxAge })` sets the lifetime in seconds. The default is an hour. :::caution Draft mode decides what the page renders. It does not decide who may see a draft. Check the visitor before you call `enable()`, and check again where the draft is read if the data is sensitive. ::: ## What changes for the editor While draft mode is on, for that visitor only: - **Prerendered pages** and their navigations are rendered now instead of being served from the build. - **Pages that export `revalidate`** are rendered for the editor, with their session, and are not kept. The copy everyone else gets is left as it was. - **Partially prerendered pages** are rendered whole instead of from the shell. - **`cache()` across requests** runs its function every time and keeps nothing, so a draft is never stored where another visitor could get it. Inside it, `draftMode()` still answers for the editor. - Every answer goes out `Cache-Control: private, no-store`, so no CDN and no browser cache keeps it. `isEnabled` is false during a build, in a page rendered for everyone and inside `cache()` across requests outside draft mode. Asking for it does not make a page dynamic: a page that only asks is still prerendered, and its stored copy is the published one. ## Reading it in a backend A Laravel function asks `$request->draft()`, beside Laravel's own `$request->prefetch()`, and may answer with what is not published yet: ```php // app/Rsc/Posts.php public function find(Request $request, string $slug): Post { $query = $request->draft() ? Post::query() : Post::published(); return $query->where('slug', $slug)->firstOrFail(); } ``` On Go, `rsckit.Drafting(ctx)` is the same question: ```go func (p *Posts) Find(ctx context.Context, slug string) (*Post, error) { if rsckit.Drafting(ctx) { return p.store.Latest(ctx, slug) } return p.store.Published(ctx, slug) } ``` Both are true only on a host call the renderer made for a visitor in draft mode, and a page's guards are asked the same. On the wire it is the header `X-RSC-Draft: 1`: the renderer checks the visitor's cookie before it sends it, never forwards one the browser sent, and the adapters believe it only past the host-call secret - a visitor who sends it to one of the app's own routes gets false. ## In production The cookie is signed, so a visitor cannot write one. It is signed with a key made from `RSC_SIGNING_SECRET`, the secret [live data](/guides/live-data) uses, and in production the server needs it: ```sh RSC_SIGNING_SECRET=… # the same on every instance: openssl rand -base64 32 ``` Without it, a cookie is never valid and draft mode stays off. In development a random key is used. During a rotation, `RSC_SIGNING_SECRET_PREVIOUS` keeps the cookies already handed out working. ### A CDN in front Homeport's edge and the [edge worker](/guides/edge-caching#serving-prerendered-pages-from-a-cdn) read `.output/edge.json`, which lists the `rsc-draft` cookie under `bypass`: a request carrying it goes to your server. Any other CDN that caches pages exporting `revalidate` needs the same rule, or it answers the editor from its copy: - **Cloudflare**: a Cache Rule that bypasses the cache when the cookie contains `rsc-draft=`. - **Others**: a rule that skips the cache for requests with the `rsc-draft` cookie. ### Offline apps An app with [offline support](/guides/offline) serves prerendered pages from its service worker. The worker cannot read the signed cookie, so draft mode also sets `rsc-draft-hint=1`, which the worker reads through the Cookie Store API and then goes to the network. Browsers without the Cookie Store API keep serving the worker's copy first and refresh it behind the page, so the editor may need to reload once. ## How it works `enable()` sets two cookies. `rsc-draft` is HttpOnly and holds an expiry time and an HMAC of it. `rsc-draft-hint` holds `1` and is for the service worker only; the server never trusts it. On each request the host searches the `Cookie` header for `rsc-draft=`. A request without it costs that search and nothing else. With it, the expiry and the signature are checked. A forged, altered or expired cookie is ignored, and the request is served like anyone else's. The signing key is derived from `RSC_SIGNING_SECRET` for this purpose alone, so the signatures a page hands out for live data can never be used as a draft cookie.