Guides · App patterns
Sign-in for your app
Sign people up and in with a password, a magic link, a provider or a passkey through one SignIn object. You decide where each session lives.
- In the schema
ext::auth::Identity
What you’ll build#
This guide wires a web app into Napalm’s built-in authentication across email and password (with verification and resets), magic links, OAuth providers such as Google and GitHub, and passkeys. One SignIn instance handles every sign-in method and persists the session so your queries run as the signed-in user. The Dart client exposes the same method names.
Turn on sign-in methods#
Every project hosts built-in sign-in with zero extra tables in your schema. A signed-in person resolves to an ext::auth::Identity bound to global caller, and enabled sign-in methods are configured on the project.
PKCE S256 sign-in across every factor
Passwords, magic-link codes, OAuth/OIDC redirects and WebAuthn passkeys all complete through /sign-in and mint an ext::auth::Identity session.
# The app's name, and where a provider or a magic link may send people back tonapalm sign-in set notes --app-name Notes --email-password \ --redirect https://app.example.com/signed-in --redirect http://localhost:5173/signed-in # A mail server, for verification codes, resets and magic links. The password is read from NAPALM_SMTP_PASSWORD.napalm sign-in email notes --host smtp.example.com --sender "Notes <sign-in@example.com>" \ --username sign-in@example.com # Each other way in. An OAuth client's secret is read from NAPALM_CLIENT_SECRET.napalm sign-in provider notes magicLinknapalm sign-in provider notes github --client-id <client-id>napalm sign-in provider notes passkeys --origin https://app.example.com napalm sign-in show notes- Redirect addresses
- A provider’s return, a magic link and a confirmation each land on an address in your app. Sign-in sends people only to listed addresses. Each
--redirectgiven replaces the list. A phone app lists the app’s own scheme, likecom.example.notes:/./ signed-in - A mail server
- Verification emails, password resets and magic links go through your SMTP server. Without a mail server, leave address confirmation off (
--no-require-verification) while you build, as the first app does. - Your own OAuth client
- Each provider signs people in to an OAuth client you registered with that provider. Give the provider
https:/as the client’s redirect address./ <your project’s address>/ sign-in/ callback
Set up SignIn#
The client library’s SignIn runs every sign-in method and stores the resulting session. Create a SignIn with a session store and pass that instance to NapalmClient.
Session-bound client and live query reset
Passing signIn to NapalmClient attaches the active bearer token to every request and restarts live subscriptions automatically on sign-out or account switch.
// src/napalm.tsimport { NapalmClient, SignIn, webStore } from 'napalm-client' export const address = import.meta.env.VITE_NAPALM_URL as string /** Who is signed in, kept in this browser. */export const signIn = new SignIn(address, { store: webStore() }) /** * Sends the session with every call, and starts its live queries again when the person * changes. */export const napalm = new NapalmClient(address, { signIn })With this wiring in place, every call and every live query runs as the signed-in person. When the person signs out or someone else signs in, the client drops the displayed rows and reruns the queries as the new person. The samples below are TypeScript in a browser. The same methods run on a phone in React Native and on a server in Next.js & React. Dart’s SignIn has the same methods for Flutter.
Sign in with email and password#
signUp registers a new ext::auth::EmailPasswordFactor and either returns a live session immediately or sends a confirmation email when address verification is required.
// src/password.tsimport { NapalmError } from 'napalm-client'import { signIn } from './napalm' /** Signs someone up. What to tell them, or nothing once they're in. */export async function signUp(email: string, password: string): Promise<string | undefined> { try { const session = await signIn.signUp(email, password, { verifyUrl: `${location.origin}/signed-in` }) // No session yet: the project confirms addresses first, and has sent the email. return session ? undefined : 'Check your email to confirm your address.' } catch (error) { if (error instanceof NapalmError && error.code === 'user_already_registered') { return 'That address already has an account. Sign in instead.' } throw error }} export async function signInWithPassword(email: string, password: string): Promise<string | undefined> { try { await signIn.withPassword(email, password) } catch (error) { if (!(error instanceof NapalmError)) throw error if (error.code === 'no_identity_found') return 'That address or password isn’t right.' if (error.code === 'verification_required') return 'Confirm your address first: check your email.' throw error }}When the project confirms addresses, the email links to your verifyUrl. One return page completes every sign-in flow that leaves the app.
// src/signed-in.ts, the page at /signed-inimport { signIn } from './napalm' // Whatever came back in the address: a provider's code, a magic link's, or a// confirmation's token.const session = await signIn.finish()// Nobody, when a confirmation link was opened in a browser the sign-up didn't start in: the// address is confirmed,// and they sign in here with their password.location.replace(session ? '/' : '/sign-in')A forgotten password#
// src/reset.tsimport { signIn } from './napalm' /** From the sign-in page: emails a link to /reset. */export const sendReset = (email: string) => signIn.sendPasswordReset(email, { resetUrl: `${location.origin}/reset` }) /** On /reset: sets the new password with the token the link carried. */export async function finishReset(password: string) { const token = new URLSearchParams(location.search).get('reset_token') if (!token) throw new Error('This link has no reset token.') // The session, when this is the browser that asked for the reset. Otherwise they sign in // with the new password. return signIn.resetPassword(password, { token })}sendPasswordReset returns the same response for an unregistered address so the form never reveals which addresses hold accounts.
Sign in with a magic link#
With magicLink on, an address is the only input. The project emails a six-digit code, or a link when the project is set to send links. sendCode returns whether a code or a link went out. An unregistered address is signed up automatically when the provider allows sign-up (--auto-signup).
// src/code.tsimport { signIn } from './napalm' /** Emails a way in. Whether it was a code to type, rather than a link to follow. */export async function sendCode(email: string): Promise<boolean> { const { isCode } = await signIn.sendCode(email, { // Used when the project sends links: where the link lands, and where a spent one goes. callbackUrl: `${location.origin}/signed-in`, redirectOnFailure: `${location.origin}/sign-in`, }) return isCode} /** The code they typed. A wrong or spent one throws verification_failed. */export const enterCode = (email: string, code: string) => signIn.withCode(email, code)Sign in with Google, GitHub and other providers#
Google, GitHub, Microsoft, Discord and Slack are built in. oidc takes any OpenID Connect issuer, such as a company’s Okta or Entra. Each issuer gets a unique --slug. Provider tokens stay inside the project, and your app only ever sees the session.
The built-in providers carry no fee. Each oidc provider on the main branch is an SSO connection at $30 a month.
// src/providers.tsimport { signIn } from './napalm' /** * The providers that are on, to draw a button for each: its name to sign in with, and what * to call it. */export const providers = async () => (await signIn.metadata()).providers /** * Leaves for the provider. It sends them back to /signed-in, where finish() ends the * sign-in. */export async function signInWith(provider: string) { location.assign(await signIn.providerUrl(provider, { redirectTo: `${location.origin}/signed-in` }))}Build the buttons from metadata() instead of hard-coding a list. metadata() returns the enabled providers with the app’s name, logo and brand color. The page then stays current when a provider is added or turned off.
Add passkeys#
The browser creates and uses a passkey at the one origin set with --origin. The person types only the address.
// src/passkey.tsimport { signIn } from './napalm' /** * Makes a passkey on this device for a new account. Nobody yet when the project confirms * addresses first. */export const signUpWithPasskey = (email: string) => signIn.addPasskey(email, { verifyUrl: `${location.origin}/signed-in` }) /** * Signs in with a passkey this device holds. Turning the prompt down throws * passkey_declined. */export const signInWithPasskey = (email: string) => signIn.withPasskey(email)Keep the session and sign out#
useSession tracks the sign-in. The value is undefined until the store is read and then holds the session or no one. signOut() ends the session at the project and clears the local copy, and the client restarts as a signed-out caller.
// src/App.tsximport { useSession } from 'napalm-client/react'import { signIn } from './napalm'import { Notes } from './Notes'import { SignInForm } from './SignInForm' export function App() { const session = useSession(signIn) // Undefined until the store has been read: draw nothing rather than flash the sign-in // form. if (session === undefined) return null if (session === null) return <SignInForm /> return ( <> <button onClick={() => signIn.signOut()}>Sign out</button> <Notes /> </> )}- Session length
- A person stays signed in for 14 days from sign-in unless you set
napalm sign-in set --session-hours(1 hour to 365 days). Activity does not extend a session. When the session ends, the person signs in again. - Session token
- The token each call carries lasts an hour. With less than a minute left,
SignInautomatically trades the session’s refresh token for a new token. Each trade retires the used refresh token. An app with several tabs renews in one tab at a time. - Signing out
signOut()ends the session at the project, so every copy of the token and refresh token stops working. The call returns whether the project was reached and clears the local session either way.signOutEverywhere()ends every session the person has on every device.- Ended sessions
signIn.session()returns no session, souseSessionshows the sign-in form. A call with an ended session gets401 invalid_session. An open live query ends withsession_endedwithin seconds.- Copied tokens
- A copied token works for at most an hour and stops working when the person signs out. A copied refresh token is caught when both holders try to spend it, and trading a retired refresh token ends the session for every holder.
- Deleting an identity
- Deleting a person’s
ext::auth::Identityends every session that person has on the session’s next request.
Pick the session store#
The store passed to SignIn controls where session tokens live and whether page scripts can read those tokens, making storage the main architectural choice in your sign-in setup.
Pluggable client backing stores
Choose webStore() for static SPAs, HttpOnly server cookies for SSR or OS Keychain and Keystore adapters on mobile.
Hourly token renewal & instant sign-out
Short-lived bearer tokens renew single-use refresh tokens hourly and terminate server-side immediately on signOut().
| Store | For | Readable by |
|---|---|---|
webStore() | An app that runs only in the browser | Readable byAny script on the page. webStore() uses localStorage. An injected script (from a compromised dependency or an injected tag) can copy the session’s tokens and use the copies from anywhere until the hour ends or the person signs out. |
| Cookies on your server | An app with a server, like Next.js | Readable byYour server only. Marking the cookie HttpOnly keeps it unreadable to page scripts. For live queries, the page gets a five-minute read-only token (signIn.pageToken()). |
| The Keychain or Keystore | A phone or desktop app | Readable byYour app only. The operating system protects the store. |
memoryStore() | A test, or a session meant to end with the page | Readable byThis SignIn only. Nothing outlasts the page. |
RFC 10017 is the IETF’s current practice for browser apps. The RFC recommends server-held tokens for apps with business or personal data and rates browser-only apps as the most exposed. Two measures reduce exposure when running without a server.
- Signing out
- Signing out ends the session at the project, so a copied token stops working. Offer “sign out everywhere” for accounts that matter.
- A content security policy
- A policy that allows scripts only from your own origin keeps most injected scripts from running at all.
In any store, the session carries only that person’s own access. Your schema’s access rules govern every row the session can read or write, and napalm endpoint --passthrough keys restricts the session to deployed queries.
Handle sign-in errors#
A refused step throws a NapalmError with a machine-readable code and a message.
| Code | Cause | Response |
|---|---|---|
no_identity_found | The address or the password is wrong. | ResponseReport the failure without naming the wrong field. |
verification_required | The address is not confirmed yet. | ResponseOffer resendVerification(email, { verifyUrl }). |
user_already_registered | A sign-up for an address that has an account. | ResponsePoint the person to sign-in or a password reset. |
verification_failed | A wrong or already used one-time code, from verification or a magic link. | ResponseLet the person try again or send a new code. |
verification_expired | A confirmation link older than one day. | ResponseSend a new link with resendVerification. |
sign_in_failed | A provider or a link returned an error. | ResponseShow message and start again. |
no_verifier | The return reached a store that did not start the sign-in. | ResponseStart again in the current browser. |
passkey_declined | The person closed the passkey prompt, or the device has no passkey for the address. | ResponseOffer another sign-in method. |
Check sign-in#
Verify provider configuration, owner-scoped query reads and cross-tab sign-out revocation before shipping.
List the settings
napalm sign-in show noteslists the app name, the redirect addresses, the session length and each provider.napalm status notesreports missing pieces, such as address confirmation with no mail server.Sign up and run a query as that person
After signing up in the app, call a deployed query that selects from a type with an owner rule. The query returns only that person’s rows. Signed out, the same call returns no rows.
Sign out in one tab
A second tab of the app also shows the sign-in form. The tabs share the store, and the second tab’s live queries empty at once. A copy of the session’s token taken earlier now gets
401 invalid_session.
The TypeScript SDK page lists every method. Sign-in documents the underlying routes for languages without a client library.