Skip to the page

Guides · Frameworks

Next.js & React

Build a Next.js app with server-side sign-in, rendering as the signed-in person, read-your-writes and live lists in the browser.

In the schema
—

What you’ll build#

This guide moves the first app’s notes onto a Next.js server with the App Router. Because access rules run inside PostgreSQL for every session, the server needs no service key to render a person’s pages. Every request to Napalm runs as the signed-in caller.

The samples target Next.js 16, where cookies() and route params are awaited and proxy.ts runs ahead of each request. On Next.js 15, use middleware.ts and export middleware instead.

WhereRuns asRole
Sign-in actions and routesNobody yetRoleRun the sign-in’s steps with SignIn and keep the session in an HttpOnly cookie.
proxy.tsThe session in the cookieRoleRenew the session’s token before a request renders, where the new token can be stored.
Server ComponentsThe session in the cookieRoleCall deployed queries for the first paint, at or after the person’s last write.
Server ActionsThe session in the cookieRoleWrite, keep the write’s bookmark and render again.
Client ComponentsA five-minute read-only token from the sessionRoleKeep the server’s rows current with live queries, straight from the project.

HttpOnly cookie sessions & proxy renewal

SignIn runs PKCE and passkey exchanges on the server, stores credentials in HttpOnly cookies and renews expiring bearers inside proxy.ts before SSR.

Read-only page tokens for live streams

Client Components open POST /subscribe directly against the project with a five-minute read-only pageToken() anchored at the server render’s Napalm-Bookmark.

Before you start#

You need a project with the first app’s schema and queries pushed and email-and-password sign-in enabled. If you do not have that project yet, Your first app sets it up in a few minutes. Run the setup commands below inside a new Next.js app.

Terminal
# The project's address for the server only; napalm endpoint notes prints the hostnameecho "NAPALM_URL=https://<project-address>" >> .env.local npm install napalm-client openapi-fetch server-onlynapalm generate notes --deployed --lang ts -o src/napalm

napalm generate writes schema.ts (types for each deployed query’s variables and rows) and live.ts (each read as a live query). Because the app uses React, napalm generate also writes hooks.ts with a live hook per read query. The routes below call two deployed queries from the starter app.

dbschema/queries/myNotes.edgeql
# The caller's notes. The rule decides whose they are: the query doesn't say.select Note { id, title, body }order by .title
dbschema/queries/addNote.edgeql
insert Note {  owner := global caller,  title := <str>$title,  body := <str>$body,}

Keep the session in a cookie#

SignIn stores session state in the backing store you pass to its constructor. Where a browser-only app uses localStorage, a server-rendered app stores three HttpOnly cookies unreadable by page scripts: the session, any in-flight OAuth PKCE verifier and the causal Napalm-Bookmark.

src/lib/napalm.ts
// src/lib/napalm.tsimport 'server-only'import createClient from 'openapi-fetch'import { cookies } from 'next/headers'import { cache } from 'react'import { NapalmClient, SignIn, type SignInStore } from 'napalm-client'import type { paths } from '@/napalm/schema'import { COOKIE } from './cookie' export const address = process.env.NAPALM_URL! /** * The session, the PKCE verifier during a redirect, and the causal bookmark: each stored in an * HttpOnly cookie unreadable by browser scripts. */const cookieStore: SignInStore = {  get: async (key) => (await cookies()).get(`napalm.${key}`)?.value ?? null,  set: async (key, value) => {    const jar = await cookies()    try {      if (value === null) jar.delete(`napalm.${key}`)      else jar.set(`napalm.${key}`, value, COOKIE)    } catch {      // Server Components cannot write cookies. src/proxy.ts renews tokens ahead of render.    }  },} /** Per-request sign-in, client and typed query bindings acting as the cookie's caller. */export const napalmFor = cache(async () => {  const signIn = new SignIn(address, { store: cookieStore })  const napalm = new NapalmClient(address, { signIn })  // Advance to the caller's last write so replica reads observe that commit.  const bookmark = await cookieStore.get('bookmark')  if (bookmark) napalm.reach(bookmark)  const db = createClient<paths>({ baseUrl: address, fetch: napalm.fetch })  return { signIn, napalm, db }}) /** Save the write's commit bookmark from a Server Action or Route Handler. */export async function keepBookmark(napalm: NapalmClient) {  if (napalm.bookmark) await cookieStore.set('bookmark', napalm.bookmark)} // src/lib/cookie.ts/** Shared cookie options matching the project's default session lifetime. */export const COOKIE = {  httpOnly: true,  secure: true,  sameSite: 'lax',  path: '/',  maxAge: 336 * 60 * 60,} as const

cache creates one instance per render no matter how many components request it. Each Server Action or Route Handler receives its own instance.

Renew the session before rendering#

A session’s bearer token lasts an hour. When less than a minute remains, SignIn trades the refresh token for a new pair and retires the previous refresh token, so the app must persist the updated session. Because a Server Component cannot write cookies during render, run renewal inside proxy.ts ahead of rendering.

src/proxy.ts
// src/proxy.tsimport { NextResponse, type NextRequest } from 'next/server'import { SignIn } from 'napalm-client'import { COOKIE } from '@/lib/cookie' export async function proxy(request: NextRequest) {  const changed = new Map<string, string | null>()  const signIn = new SignIn(process.env.NAPALM_URL!, {    store: {      get: (key) => request.cookies.get(`napalm.${key}`)?.value ?? null,      // Write onto the request so the current render reads the renewed token.      set: (key, value) => {        changed.set(key, value)        if (value === null) request.cookies.delete(`napalm.${key}`)        else request.cookies.set(`napalm.${key}`, value)      },    },  })  // Exchange the refresh token when the bearer token is near expiry.  await signIn.session().catch(() => null)   // Write onto the response so the browser persists the renewed cookies.  const response = NextResponse.next({ request })  for (const [key, value] of changed) {    if (value === null) response.cookies.delete(`napalm.${key}`)    else response.cookies.set(`napalm.${key}`, value, COOKIE)  }  return response} export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }

On most requests the proxy adds zero network latency because session() reads the cookie locally unless the bearer token is within a minute of expiry. Reusing a retired refresh token terminates the session immediately to stop token replay, so never omit proxy.ts.

Sign people in and out#

Every sign-in method is a method on SignIn, and every method stores the resulting session in the cookie. Password sign-in takes a single Server Action.

src/app/sign-in/actions.ts
// src/app/sign-in/actions.ts'use server' import { redirect } from 'next/navigation'import { NapalmError } from 'napalm-client'import { napalmFor } from '@/lib/napalm' export async function signInWithPassword(_: string | undefined, form: FormData) {  const { signIn } = await napalmFor()  try {    await signIn.withPassword(String(form.get('email')), String(form.get('password')))  } catch (error) {    // no_identity_found marks a wrong address or password; verification_required an unconfirmed address.    if (error instanceof NapalmError) return error.message    throw error  }  redirect('/notes')} export async function signOut() {  const { signIn } = await napalmFor()  await signIn.signOut()  redirect('/sign-in')}
src/app/sign-in/page.tsx
// src/app/sign-in/page.tsx'use client' import { useActionState } from 'react'import { signInWithPassword } from './actions' export default function SignInPage() {  const [message, action, isPending] = useActionState(signInWithPassword, undefined)  return (    <form action={action}>      <input name="email" type="email" autoComplete="username" required />      <input name="password" type="password" autoComplete="current-password" required />      <button disabled={isPending}>Sign in</button>      <a href="/sign-in/with/github">Sign in with GitHub</a>      {message && <p role="alert">{message}</p>}    </form>  )}

Provider sign-in leaves your site and comes back, so the flow takes two routes. Add the return address with napalm sign-in set notes --redirect https://app.example.com/sign-in/finish.

src/app/sign-in/with/[provider]/route.ts
// src/app/sign-in/with/[provider]/route.tsimport { redirect } from 'next/navigation'import { napalmFor } from '@/lib/napalm' export async function GET(request: Request, { params }: { params: Promise<{ provider: string }> }) {  const { signIn } = await napalmFor()  const { provider } = await params  // Store the PKCE verifier in the cookie and redirect to the OAuth provider.  redirect(    await signIn.providerUrl(`builtin::oauth_${provider}`, {      redirectTo: new URL('/sign-in/finish', request.url).toString(),    }),  )} // src/app/sign-in/finish/route.tsimport { redirect } from 'next/navigation'import { napalmFor } from '@/lib/napalm' export async function GET(request: Request) {  const { signIn } = await napalmFor()  // Exchange the provider's authorization code and stored verifier for a session.  const session = await signIn.finish(request.url)  redirect(session ? '/notes' : '/sign-in')}

signOut() ends the session at the project and deletes the cookie, so any copy of the session’s tokens stops working. Sign-up, magic links, password resets and address confirmation each take one Server Action around one method. Sign-in for your app covers every flow.

Passkeys#

Because only the browser can display the platform WebAuthn prompt, passkey sign-in splits cleanly across server and client: a Server Action starts the challenge and stores the PKCE verifier in an HttpOnly cookie, the page runs the credential prompt to obtain a one-time authorization code, and a second Server Action exchanges that code so the session token never touches page JavaScript.

src/app/sign-in/passkey.ts
// src/app/sign-in/passkey.ts'use server' import { redirect } from 'next/navigation'import { napalmFor } from '@/lib/napalm' /** Start a PKCE challenge while keeping the verifier in the server's HttpOnly cookie. */export async function beginPasskey() {  const { signIn } = await napalmFor()  return signIn.begin()} /** Exchange the browser's passkey authorization code using the stored cookie verifier. */export async function finishPasskey(code: string) {  const { signIn } = await napalmFor()  await signIn.finish(`/?code=${encodeURIComponent(code)}`)  redirect('/notes')} // src/app/sign-in/PasskeyButton.tsx'use client' import { SignIn } from 'napalm-client'import { beginPasskey, finishPasskey } from './passkey' export function PasskeyButton({ address, email }: { address: string; email: string }) {  const authenticate = async () => {    // Run the WebAuthn prompt against the server's challenge; the session stays on the server.    const code = await new SignIn(address).passkeyCode(email, await beginPasskey())    await finishPasskey(code)  }  return <button onClick={authenticate}>Sign in with a passkey</button>}

Render pages as the signed-in person#

A Server Component gets the request’s client and calls a deployed query. The page never checks note ownership in route code because the schema’s access rule enforces ownership inside PostgreSQL.

src/app/notes/page.tsx
// src/app/notes/page.tsximport { redirect } from 'next/navigation'import { address, napalmFor } from '@/lib/napalm'import { LiveNotes } from './LiveNotes'import { NapalmLive } from './NapalmLive' export default async function NotesPage() {  const { signIn, napalm, db } = await napalmFor()  if (!(await signIn.session())) redirect('/sign-in')   // Runs as the signed-in person; access policies filter the returned notes.  const { data } = await db.POST('/query/myNotes', { body: { variables: {} } })   return (    <NapalmLive address={address} bookmark={napalm.bookmark}>      <LiveNotes initialRows={data?.data ?? []} />    </NapalmLive>  )}

signIn.session() reads the cookie and returns no one for an expired session. A page that requires sign-in can redirect signed-out visitors before running any query.

Write from a Server Action#

A cluster with read replicas serves reads from replicas, which can trail the primary by a few milliseconds. Each Napalm response returns a bookmark naming the commit position reached. Sending the bookmark of the last write with every request holds a read until the chosen replica catches up. Because a Server Action and the next render are separate HTTP requests, a cookie carries the bookmark between the two requests.

src/app/notes/actions.ts
// src/app/notes/actions.ts'use server' import { revalidatePath } from 'next/cache'import { keepBookmark, napalmFor } from '@/lib/napalm' export async function addNote(form: FormData) {  const { napalm, db } = await napalmFor()  const { error } = await db.POST('/query/addNote', {    body: { variables: { title: String(form.get('title')), body: String(form.get('body')) } },  })  if (error) throw new Error(error.error.message ?? error.error.code)   // Save the commit bookmark before revalidating so the next server render includes the write.  await keepBookmark(napalm)  revalidatePath('/notes')}

Keep lists live in the browser#

A live query is an SSE stream the browser holds open to the project, so the stream must identify the caller. Keep the full session inside the HttpOnly cookie and hand the page a five-minute read-only token derived from that session. A page token cannot write, renew the session or sign out.

src/app/notes/token.ts
// src/app/notes/token.ts'use server' import { napalmFor } from '@/lib/napalm' /** Mint a five-minute read-only token scoped to the caller's session for browser live streams. */export async function pageToken() {  const { signIn } = await napalmFor()  return signIn.pageToken()}

The browser’s client requests a page token on connect and again before the current token expires. Pass the client the bookmark from the server render, so the live queries start no earlier than the rows already on the page.

src/app/notes/NapalmLive.tsx
// src/app/notes/NapalmLive.tsx'use client' import { useMemo, type ReactNode } from 'react'import { NapalmClient } from 'napalm-client'import { NapalmProvider } from 'napalm-client/react'import { pageToken } from './token' /** Refresh the five-minute page token shortly before expiry. */function heldToken() {  let held: { token: string; until: number } | undefined  return async () => {    if (!held || held.until - 30_000 < Date.now()) {      const next = await pageToken()      held = next ? { token: next.token, until: Date.now() + next.expiresIn * 1000 } : undefined    }    return held?.token  }} export function NapalmLive({  address,  bookmark,  children,}: {  address: string  bookmark?: string  children: ReactNode}) {  const client = useMemo(() => new NapalmClient(address, { token: heldToken() }), [address])  // Start live subscriptions at or past the server-rendered bookmark.  if (bookmark) client.reach(bookmark)  return <NapalmProvider client={client}>{children}</NapalmProvider>}
src/app/notes/LiveNotes.tsx
// src/app/notes/LiveNotes.tsx'use client' import { useMyNotes } from '@/napalm/hooks'import type { RowOf } from '@/napalm/live'import { addNote } from './actions' export function LiveNotes({ initialRows }: { initialRows: readonly RowOf<'myNotes'>[] }) {  // Undefined until the live stream's first frame, so server-rendered rows paint immediately.  const { rows, error } = useMyNotes()  const notes = rows ?? initialRows   return (    <>      <form action={addNote}>        <input name="title" placeholder="Title" required />        <input name="body" placeholder="Body" required />        <button>Add</button>      </form>      <ul>        {notes.map((note) => (          <li key={note.id}>{note.title}</li>        ))}      </ul>      {error && <p role="alert">{error.message}</p>}    </>  )}
Page token exposure
An injected script gets at most five minutes of read access as that person. A page token cannot write, cannot be traded for another token and stops working as soon as the person signs out.
Writes
Writes go through Server Actions, which hold the session. The browser sends a file’s bytes directly, so request a write-capable token for uploads with signIn.pageToken({ isReadOnly: false }).
One stream
Every hook on the page shares one connection. When the token is about to expire, the project ends the stream. The client reconnects with the next token from the same position and keeps the rows.
Signing out
Signing out ends the session and the page’s stream within seconds. Still keep NapalmLive inside the signed-in pages, so leaving those pages closes the stream at once.
Hidden parts of a page
For a hidden drawer or tab, pass { isPaused: true } to a hook. The hook closes the query and keeps the last rows.

Because the browser connects directly to the project for live streams, allow your site’s origin with napalm endpoint notes --allow-origin https://app.example.com.

Use TanStack Query#

If the app already reads through TanStack Query, subscribe once and write each result into the cache. The generated live object carries each query’s row type, so rows is typed.

src/app/notes/useNotes.ts
// src/app/notes/useNotes.ts'use client' import { useEffect } from 'react'import { useQuery, useQueryClient } from '@tanstack/react-query'import { useNapalm } from 'napalm-client/react'import { live, type RowOf } from '@/napalm/live' type Note = RowOf<'myNotes'> export function useNotes(initialNotes: readonly Note[]) {  const napalm = useNapalm()  const queryClient = useQueryClient()   // Every SSE result or patch updates the TanStack cache directly without polling.  useEffect(() => {    const subscription = napalm.subscribe(live.myNotes, {}, {      onRows: ({ rows }) => queryClient.setQueryData(['notes'], rows),    })    return () => subscription.close()  }, [napalm, queryClient])   return useQuery({    queryKey: ['notes'],    queryFn: () => initialNotes,    initialData: initialNotes,    staleTime: Infinity,  })}

Go live#

Before opening main to production traffic, lock browser origins and callback URLs, restrict sessions to deployed queries and validate schema changes on every pull request.

SSR & live-stream endpoint lockdown

Enforcing --passthrough keys and exact --allow-origin hosts confines Server Components, Server Actions and five-minute browser pageToken() streams to compiler-verified deployed queries.

napalm sign-in set --redirect
List each return address for providers and magic links: production and every preview site where you sign in.
napalm endpoint --passthrough keys
A session can then run only deployed queries. A session that sends a custom statement gets 403 deployed_query_required.
napalm endpoint --allow-origin
Allow your site’s origin for the page’s live queries, and each preview site’s origin on that preview’s branch.
napalm sign-in set --session-hours
Set how long a person stays signed in before signing in again, and match the cookies’ maxAge.
napalm schema push --review
Run the review on pull requests. The review compiles every deployed query against the new schema and refuses a change that would break a query.

Environments & going live covers the full checklist, a development branch and a branch per pull request. When a write also needs to charge a card or send an email, see Actions & background jobs. For boards, ordering and active viewers, see Realtime & collaboration.

Check sessions and live updates#

  1. Sign in and look for the token

    In the browser’s developer tools, napalm.session appears under cookies as HttpOnly, so document.cookie in the console never exposes the session. The only token visible to the page is the five-minute read-only page token on /subscribe.

  2. Add a note in a second window

    The note appears in the first window without a reload. In the network panel, one request to the project’s /subscribe stays open and receives a frame for the change.

  3. Add a note and reload at once

    The new note is in the server’s HTML. The bookmark cookie made the render wait for a replica that had the write.

  4. Sign out in one window

    The other window’s list stops updating within seconds. The next request from that window goes to the sign-in page.

Type a word or two to search every docs page.