Request and cookies
Server mode only. Read the request’s headers and cookies from a page, and write cookies from a guard.ts, a route.ts or a Server Action.
On this page
Reading request
src/routes/layout.tsximport type { LayoutProps } from '@k8ordo/framework';
import { Header } from '../components/header';
export default function RootLayout({
children,
request,
}: LayoutProps<'/'>) {
const session = request.cookies.get('session');
Reads a cookie by name
return (
<html lang="en">
<body>
<Header signedIn={session !== undefined} />
{children}
</body>
</html>
);
}A page, a layout and a not-found.tsx receive request alongside params and pathname.
request.headers: the request’s headers, asHeaders.request.cookies: the cookies by name, as aReadonlyMap: theCookieheader with what a guard or a Server Action wrote throughcookies()in the same request laid over it. The first of a repeated name wins. Surrounding quotes are removed and the value is percent-decoded. The header as it arrived isrequest.headers.get("cookie").
The generated register.gen.ts adds request to PageProps and LayoutProps under server mode only. Under static mode, a page that reads request is a type error.
src/components/greeting.tsximport type { RouteRequest } from '@k8ordo/framework/server';
export function Greeting({ request }: { request: RouteRequest }) {
const name = request.cookies.get('name') ?? 'there';
return <p>Hello, {name}</p>;
}To pass request to a child Server Component, type the prop with RouteRequest from @k8ordo/framework/server. Passing request whole to a Client Component writes every header and cookie into the page, so give it only the values it needs. The query is not part of request. A page declares the query it reads by exporting search, as described on Parameters.
Pitfall
A 'use client' page.tsx, layout.tsx or not-found.tsx receives no request. PageProps and LayoutProps still type it there, so reading it finds undefined. When the file needs request, keep it a Server Component and move the part that runs in the browser into a Client Component.
Reading and writing with cookies()
src/lib/sign-in.ts'use server';
import { href } from '@k8ordo/framework';
import { cookies, redirect } from '@k8ordo/framework/server';
import { startSession } from './sessions.server';
export type SignInState = { error?: string };
export async function signIn(
_previous: SignInState,
formData: FormData,
): Promise<SignInState> {
const session = await startSession(formData);
if (session === null) return { error: 'Wrong password' };
cookies().set('session', session.token, {
Sent as `Set-Cookie` on the response
maxAge: 60 * 60 * 24 * 30,
});
redirect(href('/account'));
}Inside a guard.ts, a route.ts or a Server Action, cookies() from @k8ordo/framework/server reads and writes cookies. The action above writes a session cookie after a successful sign-in, then redirects to /account.
A get reflects whatever was set or deleted earlier in the same request, so a Server Action reads what a guard.ts before it wrote. Every set goes out as a Set-Cookie on whichever response answers: the page re-rendered after an action, the 303 of a redirect(), or the payload the client runtime applies.
A value is percent-encoded when written to Set-Cookie and decoded when the next request brings it back. Pass set the raw string. An already encoded value is encoded twice.
Note
In the page re-rendered after an action, request.cookies holds what the action wrote, so a setting changed by a form posted without JavaScript is drawn with its new value in that very answer.
Cookie attributes
cookies().set('session', token, { maxAge: 3600, sameSite: 'strict' });Pass the cookie’s attributes as the third argument of set. An attribute left out takes a default suited to a sign-in session cookie.
path:/by default.domain: not set by default.maxAge: the lifetime in seconds.0expires the cookie at once.expires: the expiry, as aDate.httpOnly:trueby default, so page scripts cannot read the cookie.secure:trueby default, so the cookie is sent over HTTPS only.sameSite:'strict','lax'or'none','lax'by default. With'none',securedefaults totrueeven onlocalhost. Combining it withsecure: falsefails witha cookie with sameSite "none" has to be secure.
Only for a request over plain HTTP to localhost, 127.0.0.1 or [::1] does secure default to false: Chromium and Firefox keep a Secure cookie there, but Safari does not. To serve any other host over plain HTTP, pass secure: false.
Pass delete the path and domain the cookie was written with. A browser tells cookies apart by those two.
Where a preference is kept
Where a visitor’s preference is kept follows from who acts on it.
- A preference that only changes how the page looks, such as a colour scheme or a writing mode, goes in
@k8ordo/state’sdefineLocalState. An inline script that reads it withinlineRead()puts it on<html>before the first paint. The same code runs under both modes. - A preference the server answers by goes in
defineCookieState, under server mode: a guard, a form without JavaScript, or HTML that differs with it. The density the next section reads and writes only changes the look, but a form without JavaScript sets it, and the Server Action receiving that form can write a cookie, not localStorage, so it belongs here. - The language choice goes in a plain cookie the app names. The language switcher writes it with
cookieStore.set, and the guard of/passes it tonegotiateRequestaschosen. The tag is checked against the set, so it needs no declaration.
Writing the script that runs before the first paint is covered in CSP.
Choosing the language is covered in Negotiation.
Cookie state from @k8ordo/state
src/components/shell.tsx'use client';
import { useAppState } from '@k8ordo/state';
import type { ReactNode } from 'react';
import { density } from '../state';
export function Shell({ children }: { children: ReactNode }) {
const [values] = useAppState(density);
Returns the visitor’s values from the server render on
return <div data-density={values.density}>{children}</div>;
}The framework seeds every page’s states with the request’s cookies that a @k8ordo/state cookie state wrote, so useAppState(density) returns the visitor’s values from the server render on, with nothing read in a layout and passed down as a prop. Other cookies, such as a session, never go into the page.
To read the values on the server, use the definition’s parseCookies: pass it request.cookies in a page, and cookies() in a guard.ts, a route.ts or a Server Action. Defining the state is described on Cookie.
src/lib/compact.ts'use server';
import { cookies } from '@k8ordo/framework/server';
import { density } from '../state';
export async function compact() {
cookies().set(
...density.cookie({ density: 'compact' }, cookies()),
Over the current values, with the browser’s attributes
);
}To write the same cookie with cookies(), spread the name, value and attributes the definition’s cookie() returns into set. cookie() lays its first argument over the values it reads from the second, then reads them through the declaration again. A field you leave out keeps what the visitor saved.
The attributes are the ones the browser writes: Path=/, SameSite=Lax and a Max-Age of 400 days. It is not HttpOnly, because a script cannot read an HttpOnly cookie, and useAppState in the browser would no longer see the value.
To put every field back to its default, delete the cookie with cookies().delete(density.cookieName).
requestHeaders()
src/lib/report.ts'use server';
import { requestHeaders } from '@k8ordo/framework/server';
import { saveReport } from './reports.server';
export async function report(formData: FormData): Promise<void> {
const agent = requestHeaders().get('user-agent') ?? 'unknown';
Reads the request’s headers
await saveReport(formData.get('body'), agent);
}A Server Action receives only its arguments, not the request. Read the headers with requestHeaders().
Like cookies(), requestHeaders() works only inside a guard.ts, a route.ts or a Server Action. A guard.ts and a route.ts receive the Request itself, so they usually read request.headers instead.
waitUntil()
src/routes/api/chat/route.tsimport type { RouteContext } from '@k8ordo/framework';
import { waitUntil } from '@k8ordo/framework/server';
import { saveChat } from '../../../lib/chats.server';
import { generate } from '../../../lib/generate.server';
export async function POST({ request }: RouteContext<'/api/chat'>) {
const generation = await generate(await request.json());
const [forVisitor, forStore] = generation.tee();
waitUntil(saveChat(forStore));
The host keeps running until the save ends
return new Response(forVisitor);
}The host does not stop the process or the function until the promise passed to waitUntil() settles. Use it for work that goes on after the response is sent.
The work has already started when waitUntil() is called. The framework never runs it later.
It can be called from a guard.ts, a route.ts or a Server Action, and while a page or a layout renders. A stream a route.ts returned can call it too. Called outside a request, it fails with an error that starts waitUntil() needs a request.
A promise that rejects does not become an unhandled rejection. The handler logs the error once, as k8ordo: waitUntil() of POST /api/chat failed.
node dist/server.js waits before it exits, and Vercel needs @vercel/functions installed. What each host needs is covered in Deployment.
Writing to the response
A page has no way to write a status or a Set-Cookie. Only a guard.ts, or the Server Action a POST called, can write them, and both run before the page renders. Calling cookies() or responseHeaders() while a page renders fails with an error containing belongs to what answers the request.