Skip to the page

Guides · App patterns

Sign-in for your app

Authenticate users with passwords, magic links, OAuth providers or passkeys through one SignIn client while choosing where session tokens are stored.

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.

Unified PKCE sign-in

Passwords, magic codes, OAuth providers and passkeys mint the same identity session.

Run these commands to configure your app name, callback URLs, SMTP mail server and enabled sign-in providers.

Terminal
# Set the app name, enable email/password auth and register allowed callback URLsnapalm sign-in set notes --app-name Notes --email-password \  --redirect https://app.example.com/signed-in --redirect http://localhost:5173/signed-in # Configure SMTP for verification emails, password resets and magic links (reads NAPALM_SMTP_PASSWORD)napalm sign-in email notes --host smtp.example.com --sender "Notes <sign-in@example.com>" \  --username sign-in@example.com # Enable magic links, GitHub OAuth (reads NAPALM_CLIENT_SECRET) and passkeysnapalm 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
OAuth callbacks, magic links and email verification links must target an allowed return URL. Passing --redirect replaces the existing allowlist. Native mobile apps register a reverse-DNS custom scheme such as com.example.notes://signed-in.
Mail server
Verification emails, password resets and magic links send through your configured SMTP server. During local setup without SMTP, pass --no-require-verification to skip email confirmation.
OAuth clients
Register your own OAuth application with each provider and set the provider callback URL to https://<your-project-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.

src/napalm.ts
// src/napalm.tsimport { NapalmClient, SignIn, webStore } from 'napalm-client' export const address = import.meta.env.VITE_NAPALM_URL as string /** Persists the active user session in browser storage. */export const signIn = new SignIn(address, { store: webStore() }) /** * Attaches the active session to every request and restarts live queries when the caller * changes. */export const napalm = new NapalmClient(address, { signIn })

With this wiring in place, every query and live subscription runs as the signed-in user. Signing out or switching accounts clears cached rows immediately and reconnects under the new session. The browser TypeScript methods shown below also run in React Native and Next.js & React, and the Dart SDK exposes identical methods for Flutter.

Session-bound client

NapalmClient attaches active bearer tokens and resets live subscriptions when accounts change.

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.ts
// src/password.tsimport { NapalmError } from 'napalm-client'import { signIn } from './napalm' /** Registers a new account and returns a prompt when email confirmation is required. */export async function signUp(email: string, password: string): Promise<string | undefined> {  try {    const session = await signIn.signUp(email, password, { verifyUrl: `${location.origin}/signed-in` })    // When address confirmation is required, signUp sends the verification email and returns null.    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 email verification is enabled, the confirmation link opens your verifyUrl. One callback route completes every redirect-based sign-in flow.

src/signed-in.ts
// src/signed-in.ts (mounted at /signed-in)import { signIn } from './napalm' // Exchanges an OAuth authorization code, magic-link token or email verification token.const session = await signIn.finish()// Returns null when a verification link opens in a different browser. The email is confirmed,// so redirect to sign-in.location.replace(session ? '/' : '/sign-in')

Password resets#

src/reset.ts
// src/reset.tsimport { signIn } from './napalm' /** Sends a password reset link pointing to /reset. */export const sendReset = (email: string) =>  signIn.sendPasswordReset(email, { resetUrl: `${location.origin}/reset` }) /** Updates the password using the reset_token query parameter on /reset. */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.')  // Returns a session when completed in the same browser, or null if opened elsewhere.  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 enabled, users sign in with only an email address. Depending on your provider settings, Napalm emails either a six-digit code or a sign-in link, and sendCode reports which mode was sent via isCode. Passing --auto-signup creates accounts automatically for new email addresses.

src/code.ts
// src/code.tsimport { signIn } from './napalm' /** Sends a magic code or link by email and returns true when the user should enter a 6-digit code. */export async function sendCode(email: string): Promise<boolean> {  const { isCode } = await signIn.sendCode(email, {    // Used when magic links are configured instead of 6-digit codes.    callbackUrl: `${location.origin}/signed-in`,    redirectOnFailure: `${location.origin}/sign-in`,  })  return isCode} /** Exchanges the 6-digit code for a session, or 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, and oidc connects any OpenID Connect issuer such as Okta or Microsoft Entra under a unique --slug. Upstream provider tokens stay on the server, so your app receives only the Napalm session.

Built-in OAuth providers carry no extra fee. Each oidc provider on the main branch bills as an SSO connection at $30 per month.

src/providers.ts
// src/providers.tsimport { signIn } from './napalm' /** Lists enabled OAuth and OIDC providers so the UI can render sign-in buttons dynamically. */export const providers = async () => (await signIn.metadata()).providers /** Redirects to the identity provider, which returns the user to /signed-in for finish(). */export async function signInWith(provider: string) {  location.assign(await signIn.providerUrl(provider, { redirectTo: `${location.origin}/signed-in` }))}

Render provider buttons from signIn.metadata() rather than hard-coding a provider list. Because metadata() returns enabled providers alongside your app’s configured name, logo and brand color, your sign-in screen updates automatically when you add or disable a provider.

Add passkeys#

The browser registers and authenticates WebAuthn passkeys bound to the origin configured with --origin. Users enter only their email address.

src/passkey.ts
// src/passkey.tsimport { signIn } from './napalm' /** Registers a passkey for a new account. Returns null until verified when email confirmation is required. */export const signUpWithPasskey = (email: string) =>  signIn.addPasskey(email, { verifyUrl: `${location.origin}/signed-in` }) /** Authenticates with a passkey on this device, or throws passkey_declined if dismissed. */export const signInWithPasskey = (email: string) => signIn.withPasskey(email)

Keep the session and sign out#

useSession tracks the active caller in React. The hook returns undefined while reading storage, null when signed out and the Session once signed in. Calling signOut() revokes the session on the server, clears local storage and resets the client to an unauthenticated state.

src/App.tsx
// 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)  // Wait for storage hydration before choosing between the app and 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 user stays signed in for 14 days from authentication unless you set napalm sign-in set --session-hours (1 hour to 365 days). Activity does not extend the deadline, so users sign in again once the session expires.
Bearer renewal
Each bearer token lasts an hour. When less than a minute remains, SignIn exchanges the single-use refresh token for a fresh pair and retires the spent refresh token. Across multiple open tabs, only one tab runs the exchange.
Signing out
signOut() revokes the session on the server so every copy of its bearer and refresh tokens stops working, and clears local storage even when offline. signOutEverywhere() revokes every active session for that user across all devices.
Expired sessions
When a session expires, signIn.session() returns null and useSession renders your sign-in screen. Requests carrying an expired token fail with 401 invalid_session, and open live streams close with session_ended within seconds.
Token replay defense
A stolen bearer token works for at most an hour and stops working immediately on sign-out. Refresh tokens are single-use, so replaying a retired refresh token revokes the entire session for every holder.
Deleting an identity
Deleting a user’s ext::auth::Identity invalidates every active session for that user on the next request.

Pick the session store#

The store passed to SignIn controls where session tokens live and whether page scripts can read those tokens.

Pluggable session stores

Persist sessions in localStorage, server HttpOnly cookies or native mobile Keychain.

Hourly token renewal

Bearer tokens renew hourly with single-use refresh tokens and revoke on sign-out.

Compare the four built-in storage patterns by app architecture and script visibility.

StoreForReadable by
webStore()Browser-direct SPAsReadable byAny script on your origin. webStore() persists tokens in localStorage, so an injected script can read tokens until the one-hour bearer expires or the user signs out.
Server HttpOnly cookiesServer-rendered apps (Next.js)Readable byYour server only. Marking cookies HttpOnly hides session tokens from page scripts while the browser uses five-minute read-only tokens (signIn.pageToken()) for live streams.
Keychain or KeystoreMobile and desktop appsReadable byYour native app bundle only, isolated by the operating system.
memoryStore()Automated tests or ephemeral tabsReadable byThe in-memory SignIn instance only. Closing or reloading the page discards the session.

RFC 10017 recommends server-held HttpOnly cookies for browser apps handling sensitive business or personal data because browser-only token stores remain exposed to script injection. When you ship a static SPA without a server, combine two defenses.

Server-side revocation
Calling signOut() revokes tokens on the project immediately, and signOutEverywhere() revokes all devices at once.
Content Security Policy
Serving a strict Content-Security-Policy header that restricts script-src to your own origin blocks most script-injection vectors.

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.

CodeCauseResponse
no_identity_foundEmail address or password did not match an account.ResponseShow a generic invalid-credentials message without revealing which field failed.
verification_requiredThe email address has not been confirmed yet.ResponsePrompt the user to check email and offer resendVerification(email, { verifyUrl }).
user_already_registeredSign-up attempted for an email address that already has an account.ResponseDirect the user to sign in or reset their password.
verification_failedInvalid or already-spent one-time code from email verification or a magic link.ResponsePrompt the user to re-enter the code or request a fresh code.
verification_expiredConfirmation link is older than one day.ResponseSend a fresh link with resendVerification.
sign_in_failedOAuth provider or callback link returned an error.ResponseDisplay error.message and restart sign-in.
no_verifierCallback opened in a browser or device that did not initiate the PKCE flow.ResponseRestart sign-in in the current browser.
passkey_declinedThe user dismissed the passkey prompt or has no passkey on this device.ResponseOffer password, magic-code or OAuth sign-in instead.

Check sign-in#

Verify provider configuration, owner-scoped query reads and cross-tab sign-out revocation before shipping.

  1. List the settings

    napalm sign-in show notes lists the app name, redirect URLs, session lifetime and enabled providers. napalm status notes flags incomplete settings, such as email verification without an SMTP server.

  2. 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.

  3. Sign out in one tab

    Open the app in two tabs and sign out in the first tab. Because both tabs share webStore(), the second tab clears active live queries and returns to the sign-in screen immediately, and any previously copied bearer token fails with 401 invalid_session.

The TypeScript SDK page lists every method. Sign-in documents the underlying routes for languages without a client library.

Type a word or two to search every docs page.