--- title: "Authentication" description: "Authenticate Beignet requests with auth ports, route metadata, HTTP boundary hooks, and Better Auth." url: "https://www.beignetjs.com/authentication" markdown_url: "https://www.beignetjs.com/markdown/authentication.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Authentication Authentication answers "who is making this request?" In Beignet, the recommended shape is: 1. Auth provider or app adapter installs an auth port. 2. Hooks enforce route-level authentication at the HTTP boundary. 3. The session and request actor are added to context. 4. Use cases call `requireUser(ctx)` from `@beignet/core/ports` when a workflow needs a signed-in user. Authorization is separate. It answers whether that user may perform a specific business action. See [Authorization](https://www.beignetjs.com/markdown/authorization.md). ## Auth port Beignet apps use the shared `AuthPort` shape from `@beignet/core/ports`. Production apps can replace the anonymous adapter with Better Auth or another session system without changing hooks or use cases. ```typescript import type { AuthPort, AuthSession } from "@beignet/core/ports"; export type AuthUser = { id: string; email?: string; }; export type AppAuthSession = AuthSession; export type AppAuthPort = AuthPort; ``` Keep this as an app-facing interface. Your use cases and hooks should not need to know whether the user came from Better Auth, JWT, a session cookie, or a test adapter. ## Route metadata Contracts can describe authentication requirements as metadata for OpenAPI, docs, clients, and conventions: ```typescript export const createPost = posts .post("/") .meta({ auth: "required" }) .body(CreatePostInput) .responses({ 201: PostOutput }); ``` Metadata is not security by itself. Runtime enforcement should be visible in route wiring with route hooks. ## HTTP boundary hooks Use `createAuthHooks(...)` to reject unauthenticated requests before the route handler runs: ```typescript import { createAuthHooks } from "@beignet/core/server"; import { defineRouteGroup } from "@/lib/routes"; import type { AppContext } from "@/app-context"; export const auth = createAuthHooks()({ resolve: ({ ctx }) => { if (!ctx.auth) return null; return { user: ctx.auth.user }; }, }); ``` The outer call binds the app context; the inner call takes the auth options and infers the added context fields from what `resolve` returns. The helper returns explicit route-hook factories: | Hook | Behavior | | ----------------- | ------------------------------------------------------------------------------------------------ | | `auth.public()` | Mark the route as intentionally public | | `auth.optional()` | Resolve auth when present and add optional auth fields to `ctx` | | `auth.required()` | Resolve auth, return a framework-owned `401` when missing, and add authenticated fields to `ctx` | Attach those hooks in feature route groups: ```typescript export const postRoutes = defineRouteGroup({ name: "posts", hooks: [auth.optional()], routes: [ { contract: listPosts, useCase: listPostsUseCase }, { contract: createPost, hooks: [auth.required()], useCase: createPostUseCase, }, ], }); ``` The hook guards the HTTP boundary; the bound use case reads the resolved session from its own context (for example through `requireUser(ctx)` from `@beignet/core/ports`). Full `handle` routes that need hook-added fields typed on `ctx` can wrap the route in `defineRoute`; binder routes (routes registered as `{ contract, useCase }` — see [Server](https://www.beignetjs.com/markdown/server.md)) do not need it. Auth failures are framework-owned, so your business contract does not need to declare every infrastructure response such as malformed JSON, missing auth, or rate limits. The `server/context.ts` blueprint should resolve the session once and define the baseline context shape before route hooks run: ```typescript // server/context.ts import { createAnonymousActor, createUserActor } from "@beignet/core/ports"; import { defineServerContext } from "@beignet/core/server"; import type { AppContext } from "@/app-context"; export const appContext = defineServerContext< AppContext, AppContext["ports"] >()({ gate: (ports) => ports.gate, request: async ({ ports, req, requestId, trace }) => { const auth = await ports.auth.getSession(req); return { actor: auth ? createUserActor(auth.user.id) : createAnonymousActor(), auth, requestId, ...trace, ports, }; }, }); ``` `auth` is the resolved provider session or `null`. Route hooks enforce HTTP access and may narrow handler `ctx`, but they should not be the only place that derives the app's audit actor. ## Use-case helpers Use cases should still require a user when the workflow needs one. That keeps the rule active when the workflow is called from HTTP, jobs, scripts, event handlers, or tests. Beignet exports context helpers for this: | Helper | Returns | Default error | | ------------------------- | --------------------------------------------------------- | ----------------------------------------------- | | `requireSession(ctx)` | The full `ctx.auth` session | `AuthUnauthorizedError` (framework-owned `401`) | | `requireUser(ctx)` | The session user, inferred from the app's `ctx.auth` type | `AuthUnauthorizedError` (framework-owned `401`) | | `requireUserId(ctx)` | The user's `id` string | `AuthUnauthorizedError` (framework-owned `401`) | | `requireTenant(ctx)` | The `ctx.tenant` activity tenant | `TenantRequiredError` (framework-owned `403`) | | `requireTenantId(ctx)` | The tenant's `id` string | `TenantRequiredError` (framework-owned `403`) | | `requireTenantScope(ctx)` | A branded `TenantScope` for repository boundaries | `TenantRequiredError` (framework-owned `403`) | ```typescript import { requireUser } from "@beignet/core/ports"; import { requireTenantScope } from "@beignet/core/tenancy"; const createPost = useCase .command("posts.create") .input(CreatePostInput) .output(PostOutput) .run(async ({ ctx, input }) => { const user = requireUser(ctx); const scope = requireTenantScope(ctx); return ctx.ports.posts.create( { ...input, authorId: user.id, }, scope, ); }); ``` The user type is inferred from the app's `ctx.auth` session, so `user` above is the app's own `AuthUser` shape without casts. The server maps `AuthUnauthorizedError` to a framework-owned `401` with code `UNAUTHORIZED` and `TenantRequiredError` to a framework-owned `403` with code `TENANT_REQUIRED`. The errors themselves expose matching `status` values of `401` and `403`, so app-owned error handling can inspect them consistently. Contracts do not need to declare these infrastructure responses. Pass `options.error` when a workflow should throw an app-catalog error instead: ```typescript const user = requireUser(ctx, { error: () => appError("Unauthorized") }); ``` App-owned wrappers around these helpers are still fine when they add app semantics, but the core helpers are the default. ## Better Auth provider Use `@beignet/provider-auth-better-auth` when Better Auth owns session lookup: ```bash bun add @beignet/core @beignet/provider-auth-better-auth better-auth@1.7.26 ``` The provider supports Better Auth `>=1.7.7 <1.8.0`. The starter pins Better Auth to `1.7.26` so clean installs use the version Beignet validates in generated apps. When upgrading from Better Auth versions before `1.7.7`, update all servers sharing verification storage and all OAuth Proxy participants together. Request new Magic Links and restart pending OAuth or SAML sign-ins; pre-upgrade links and state cannot complete. The token fix needs no new tables; apps upgrading from `1.7.0`–`1.7.2` also need the account schema change below. If you customize verification identifier storage, follow the [Better Auth upgrade guidance](https://github.com/better-auth/better-auth/releases/tag/v1.7.7). After upgrading Better Auth or changing its plugins, regenerate the schema for your database adapter and apply the resulting migration before deployment. Apps that enable `twoFactor()` need the current [two-factor schema](https://better-auth.com/docs/plugins/2fa#schema), including `failedVerificationCount` and `lockedUntil`. The standard Beignet starter does not enable two-factor authentication, so its default auth configuration does not require those fields. ### Upgrade an existing app to Better Auth 1.7 Better Auth `1.7.3` and newer identify accounts by `(providerId, accountId)`. New Beignet starters use this schema without an `issuer` column. If you installed the schema from Better Auth `1.7.0`–`1.7.2`, make the legacy `account.issuer` column nullable and remove its compound unique index in both your schema and a reviewed migration. Preserve existing account rows and issuer values; removing the column is optional cleanup. SQLite needs a table rebuild to relax `NOT NULL`. Apply the migration before deploying the updated runtime, then verify new sign-ups and existing-account sign-ins. Check for duplicate `(providerId, accountId)` pairs before upgrading. If distinct identity providers share a provider ID, give them separate IDs and update the matching account rows without merging users. Follow Better Auth's [1.7 upgrade guide](https://better-auth.com/docs/guides/1-7-upgrade-guide#account-identity-keeps-the-provider-key) for database-specific steps and provider-specific changes. ```typescript import { createBetterAuthProvider } from "@beignet/provider-auth-better-auth"; import { auth } from "@/lib/better-auth"; export const providers = [ createBetterAuthProvider({ auth }), ]; ``` The provider wraps an already configured Better Auth instance and installs the same shared `AuthPort` on `ctx.ports.auth`. Apps that need custom provider setup can use the lower-level adapter inside an app-local provider: ```typescript // server/providers.ts import { createProvider } from "@beignet/core/providers"; import { createBetterAuthPort } from "@beignet/provider-auth-better-auth"; import { auth } from "@/lib/better-auth"; export const appAuthProvider = createProvider({ name: "app-auth", setup({ ports }) { return { ports: { auth: createBetterAuthPort({ auth, instrumentation: ports }), }, }; }, }); export const providers = [appAuthProvider] as const; ``` Define and register `appAuthProvider` in `server/providers.ts`; provider audit recognizes the direct adapter there as valid registration. Both forms leave ownership of the Better Auth instance with the app and emit the same redacted auth events. Better Auth still owns its own login, signup, callback, and session routes. Mount those routes beside your Beignet API routes. In a Next.js 16 app, you can add a root `proxy.ts` for faster redirects when a request does not have a Better Auth session cookie. Treat this as an app-specific UX gate only: the static matcher should reflect your protected URL shape, and the Beignet layout/session checks, route hooks, and use-case helpers remain the real authorization boundary. ```typescript import { getSessionCookie } from "better-auth/cookies"; import { NextResponse, type NextRequest } from "next/server"; export function proxy(request: NextRequest) { const sessionCookie = getSessionCookie(request); if (!sessionCookie) { return NextResponse.redirect(new URL("/sign-in", request.url)); } return NextResponse.next(); } export const config = { matcher: ["/dashboard/:path*", "/settings/:path*"], }; ``` Do not use this cookie-only check as proof of authentication. A request with a stale or manually created cookie must still be rejected by `auth.api.getSession`, `ctx.ports.auth`, route hooks, policies, or `requireUser(ctx)` before protected data or actions run. Route groups such as `app/(app)` are not part of the URL, so keep the matcher aligned with your app's real paths. ## Account recovery and email verification New apps created with `--providers mail-resend` include password recovery and email verification. Configure `RESEND_API_KEY` and a verified `RESEND_FROM` before using the email flows. The starter's placeholder values do not deliver mail. A starter without a mail provider keeps its basic sign-in/sign-up flow. For an existing Next.js app: ```bash bun beignet provider add mail-resend bun install bun beignet make auth --dryRun bun beignet make auth ``` You can use an already configured SMTP or custom `MailerPort` instead of adding Resend. The generator checks the installed app's typed `getServer().ports.mailer` without booting it. It adds app-owned email callbacks, pages, and tests. It preserves unrelated Better Auth options and refuses conflicting email settings or nonliteral configuration before writing, including with `--force`. Static computed keys are checked too; dynamic keys and existing helper identifiers (`authEmail`, `authSettings`, `createAuthEmailOptions`) require manual integration. Existing custom auth configuration can use [the manual setup below](https://www.beignetjs.com/markdown/authentication.md#configure-recovery-manually). | File or route | Responsibility | | ------------------------------------------------- | ---------------------------------------------------------------------- | | `lib/auth-email.ts` | Mail templates, one-hour expiry, and reset session revocation | | `lib/auth-settings.ts` | Shared verification policy and navigation URLs | | `features/account/components/auth-email-form.tsx` | Recovery, resend, and verification status UI | | `/forgot-password` | Request a reset link with an account-existence-neutral response | | `/reset-password` | Set and confirm a new password; handle invalid, expired, or used links | | `/verify-email` | Check-email, resend, success, and expired-link states | | `features/account/tests/auth-email.test.ts` | Checks for reset and verification behavior without sending real email | Standard starter sign-in, sign-up, and settings screens are connected automatically. Custom screens are preserved. Connect them by linking to `/forgot-password` and `/verify-email`, passing `authSettings.verificationCallback` to `authClient.signUp.email`, and directing `EMAIL_NOT_VERIFIED` sign-in errors to `/verify-email`. After signup, direct users to `/verify-email` when enforcement is required, or to your app otherwise. Set `authSettings.signInPath` for custom login routes. Render `EmailVerificationStatus` in your account UI. With the starter defaults, email changes stay pending until the new address is confirmed. The starter keeps that address in the settings form, explains that the current address is still in use, and offers “Save and resend verification.” Resend by calling `authClient.changeEmail({ newEmail, callbackURL: authSettings.emailChangeCallback })` again. `sendVerificationEmail` verifies the current account address; it cannot resend a pending change to another address. Custom settings screens should retain the pending address and only show the email as changed once the session confirms it. For custom Better Auth configurations, enable `user.changeEmail.enabled` to allow address changes. To keep an address change pending until verification, supply a `sendVerificationEmail` callback and leave `user.changeEmail.updateEmailWithoutVerification` false or omitted. Setting that option to true lets an unverified user change their address immediately. API-only starters include callbacks and tests but no pages. For an existing app, `beignet make auth --ui=false` has the same effect. Supply your own reset redirect, verification callback, and client UI in that case. The generator targets Next.js; Fetch hosts can use the same app-owned Better Auth callbacks with their own server loader and route mounting. Confirming a replacement address preserves the account's prior verification status in Better Auth 1.7.26. An account that has not completed verification must also follow the regular verification email for its new address. The `emailChangeCallback` opens `/verify-email?emailChanged=1`, where the page checks the session's `user.emailVerified` value. If the account is unverified or no session is available, the page offers the regular verification form. Custom screens should distinguish address confirmation from account verification and call `authClient.sendVerificationEmail(...)` when verification is needed. ### Choose the verification policy The generated policy sends verification mail on signup and allows password sign-in before verification. Change `requireEmailVerification` to `true` in `lib/auth-settings.ts` to require verification before password sign-in. That value is shared by the server and generated UI. Signup verification does not automatically sign the user in; Better Auth handles email-change sessions separately. Existing sessions are not retroactively revoked by changing the policy; apps that require verification for particular actions must enforce it in those use cases too. Reset links expire after one hour and can be consumed once. A successful reset revokes all existing sessions, and the user signs in again on each device. Better Auth owns passwords, tokens, expiry, and verification records; these flows do not add Beignet token tables or a second auth system. ### Configure recovery manually If `make auth` rejects custom configuration, connect the callbacks below to your existing Better Auth instance. This recipe assumes that Better Auth's routes are mounted and your server exposes a configured `MailerPort` at `ports.mailer`. It configures delivery and policy; you supply the pages in your existing UI. First, create `lib/auth-settings.ts`. Replace the navigation paths if your app uses different routes. Keep this file safe to import from browser code: ```typescript // lib/auth-settings.ts export const authSettings = { requireEmailVerification: false, signInPath: "/sign-in", verificationCallback: "/verify-email?verified=1", emailChangeCallback: "/verify-email?emailChanged=1", } as const; ``` Create `lib/auth-email.ts` to define the callbacks and their defaults. If either file or helper name already exists, merge the configuration or choose another name and adjust the imports below. ```typescript // lib/auth-email.ts import type { MailerPort } from "@beignet/core/mail"; import type { BetterAuthOptions } from "better-auth"; export function createAuthEmailOptions({ getMailer, requireEmailVerification, }: { getMailer: () => Promise; requireEmailVerification: boolean; }) { return { emailAndPassword: { enabled: true, requireEmailVerification, revokeSessionsOnPasswordReset: true, resetPasswordTokenExpiresIn: 60 * 60, async sendResetPassword({ user, url }) { const mailer = await getMailer(); await mailer.send({ to: user.email, subject: "Reset your password", text: `Choose a new password using this link (expires in one hour):\n\n${url}`, }); }, }, emailVerification: { sendOnSignUp: true, sendOnSignIn: false, autoSignInAfterVerification: false, expiresIn: 60 * 60, async sendVerificationEmail({ user, url }) { const mailer = await getMailer(); await mailer.send({ to: user.email, subject: "Verify your email address", text: `Verify your email using this link (expires in one hour):\n\n${url}`, }); }, }, } satisfies Pick; } ``` In your existing `lib/better-auth.ts`, add these imports and initialize the callbacks before the `betterAuth(...)` call: ```typescript // lib/better-auth.ts (excerpt) import { createAuthEmailOptions } from "@/lib/auth-email"; import { authSettings } from "@/lib/auth-settings"; const authEmail = createAuthEmailOptions({ requireEmailVerification: authSettings.requireEmailVerification, async getMailer() { const { getServer } = await import("@/server"); return (await getServer()).ports.mailer; }, }); ``` Merge the following fields into that call. These are excerpts, not a replacement for the whole file: retain your database, secret, base URL, trusted origins, plugins, and other user settings. Review existing recovery callbacks and policy options before replacing them; keep other password options alongside the spread. ```typescript // lib/better-auth.ts (excerpt) export const auth = betterAuth({ // Keep your existing database, secret, origins, plugins, and user settings. emailAndPassword: { ...authEmail.emailAndPassword, // Keep your other password options here. }, emailVerification: authEmail.emailVerification, }); ``` The lazy `getMailer` callback starts your server's mail provider even when an auth request arrives first. For a custom server path or Fetch host, adapt `getMailer` to return your server's mailer. Keep delivery inside the awaited callback. Connect your existing client UI to these Better Auth methods: - Request a reset link with `authClient.requestPasswordReset({ email, redirectTo: "/reset-password" })`. - At `/reset-password`, handle the `error` query parameter and missing tokens before showing the form. Read `token` from the URL and submit `authClient.resetPassword({ token, newPassword })`. Use a POST form and remove the token from the browser URL after a successful reset. - At `/verify-email`, show callback errors before success and resend with `authClient.sendVerificationEmail({ email, callbackURL: authSettings.verificationCallback })`. Use `changeEmail` for a pending address change as described above. Also connect signup and unverified sign-in navigation as described above. If you use different page paths, update `redirectTo`, `verificationCallback`, and `emailChangeCallback` to match. ### Configure delivery Both the generated and manual setup send through your server's mailer. Configure real credentials before testing delivery, and set Better Auth's base URL to the public origin that should appear in emails (`BETTER_AUTH_URL` in the starter). Better Auth 1.7 keeps password-reset responses generic even when delivery fails; signup can also succeed while its verification email fails. Monitor provider and Better Auth delivery errors and let users request another email. A public success response is not proof of delivery. The generated callbacks do not log email bodies, passwords, or token URLs. Keep trusted origins restricted, and configure Better Auth's production rate limiting and shared storage for your deployment. The generic response does not guarantee identical response timing for known and unknown accounts. Memory mail is for development and tests; it does not deliver messages to an inbox. Configure a [mail provider](https://www.beignetjs.com/markdown/mail.md), such as Resend or SMTP, before deploying account recovery. ### Verify the setup For a mail-enabled starter or an app configured with `make auth`, run the generated account checks from the app directory: ```bash bun test features/account/tests/auth-email.test.ts ``` These checks use memory delivery and need no mail credentials. If you configured recovery manually, add equivalent checks for your callbacks and routes. With real mail delivery configured, verify the following using a test account: 1. Sign up with an address you control and follow the verification email. The account UI should show a verified address. With enforcement enabled, password sign-in should fail before verification and succeed afterward. 2. Request a password reset at `/forgot-password`. Follow the email and choose a new password. The new password should work, the old password should fail, and previously signed-in sessions should lose access to protected routes. 3. Open the same reset link again and try to submit another password. It should fail. A link older than one hour should also fail; requesting a fresh link should let you recover. 4. In the starter settings, request an email address change. The current address should stay in use until you confirm the replacement address. Use “Save and resend verification” to request another link, then confirm the new address and refresh the session. Repeat with an initially unverified account: the confirmation page should offer a regular verification email for the new address. Follow that email before expecting the account UI to show verified. The manual recipe does not create the generated test file or pages. Apply the same checks to your own UI and account settings, using the policy you selected. See Better Auth's [email/password documentation](https://better-auth.com/docs/authentication/email-password) and [email verification documentation](https://better-auth.com/docs/concepts/email) for additional application policy options. ## Devtools When the devtools provider is installed before the Better Auth provider, auth checks appear in the Auth tab. The provider records `getSession`, `getUser`, and `requireUser` operations with authenticated status and duration. User and session objects are not recorded. ## Testing Tests can pass an auth adapter directly: ```typescript import { createStaticAuth } from "@beignet/core/ports"; const auth = createStaticAuth({ user: { id: "user_1", email: "user@example.com", }, }); const ctx = { user: await auth.getUser(new Request("http://test.local")), ports: { auth, posts: createInMemoryPosts(), }, }; ``` For unauthenticated tests, return `null` and assert that the use case throws `AuthUnauthorizedError` (code `UNAUTHORIZED`). ## Typed credential headers Service-to-service surfaces such as internal APIs and webhook receivers authenticate with credentials in request headers instead of a user session. Declare a `headers` schema on the auth hooks for these surfaces. The hook validates the raw lowercase request header record itself, so `resolve` receives typed header values without casting and without depending on each route's contract header schema: ```typescript import { createServiceActor, createTenant } from "@beignet/core/ports"; import { createAuthHooks } from "@beignet/core/server"; import { z } from "zod"; import type { AppContext } from "@/app-context"; const serviceHeadersSchema = z.object({ authorization: z .string() .regex(/^Bearer\s+\S+$/i, "Expected Authorization: Bearer "), }); export const serviceAuth = createAuthHooks()({ name: "internal.service", headers: serviceHeadersSchema, resolve: async ({ ctx, headers }) => { const apiKey = headers.authorization.replace(/^Bearer\s+/i, ""); const principal = await ctx.ports.apiKeys.verify({ apiKey }); if (!principal) return null; return { actor: createServiceActor(principal.id, { displayName: principal.displayName, metadata: { auth: "api-key", scopes: [...principal.scopes], }, }), tenant: createTenant(principal.tenantId), }; }, }); ``` Keep the verifier behind an app port such as `ctx.ports.apiKeys` rather than reading environment variables in the hook. That makes route tests independent from module-load env snapshots and lets production adapters verify hashed API keys, tenant membership, rotation status, and scopes without changing route wiring. See [Tenancy](https://www.beignetjs.com/markdown/tenancy.md) for resolving tenant scope from verified API keys, sessions, and organization membership. On `required()` routes, a header schema failure or a `null` return from `resolve` is an authentication failure: a framework-owned `401`, not a `422`. On `optional()` routes a schema failure skips auth resolution, and `public()` never parses headers. Session-based hooks do not need a `headers` schema. Without one, `resolve` still receives the raw lowercase header record. ## Read next - [Hooks](https://www.beignetjs.com/markdown/hooks.md) for hook lifecycle details. - [Tenancy](https://www.beignetjs.com/markdown/tenancy.md) for tenant resolution and tenant-aware policies. - [Authorization](https://www.beignetjs.com/markdown/authorization.md) for policies and ownership checks. - [Providers](https://www.beignetjs.com/markdown/providers.md) for provider lifecycle and setup order.