# Dotpress > A lightweight, decorator-free TypeScript framework for building end-to-end typed backend APIs. This documentation covers Dotpress 2. Dotpress 1 (the `dotpress` package, and `@dotpress/auth` 1.x) has a different API: do not use it, nor code written for it. Dotpress 2 is in beta. Install `@dotpress/auth` with the `beta` tag, since its `latest` tag is still 1.x: `npm install @dotpress/auth@beta`. Key rules: - Declare routes with `defineRoute()` and Zod 4 schemas: the types of the request and of the response are inferred, never passed as generics. - Handlers and middlewares return their errors (`notFoundError()`, `forbiddenError()`…): they do not throw them. - The packages are ES modules, for Node.js 22.12 or later and TypeScript 5.5 or later, with `strict` enabled. - Apps are tested in memory with `@dotpress/testing`, on Vitest. https://dotpress.dev/llms.txt is an index of the pages below, each also available on its own in Markdown. --- url: https://dotpress.dev/getting-started/introduction.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Introduction Dotpress is a lightweight TypeScript framework for backend APIs. You declare each route with `defineRoute()`: a path, Zod schemas and a handler. Dotpress validates the request, types it from your schemas and from the path, and runs your app on the HTTP server you choose. ```ts import { createRouteGroup, notFoundError } from '@dotpress/core' declare const members: { find(orgId: string, id: string): Promise<{ id: string; name: string } | undefined> } // Every route of the group starts with /orgs/:orgId/members const orgMembers = createRouteGroup('/orgs/:orgId/members') orgMembers.defineRoute({ path: '/:memberId', handler: async ({ req }) => { const member = await members.find(req.params.orgId, req.params.memberId) return member ?? notFoundError('Member not found') }, }) ``` Hover `req.params`: `orgId` comes from the group, `memberId` from the route. No annotation, no decorator, no class. ## Why Dotpress Building an API in TypeScript usually means picking one of two compromises: - **A minimal HTTP framework** (Express, Fastify, Hono): quick to start, but the validation, the request types, the error format and the documentation are yours to write, and to keep in sync by hand. Middleware chains grow, and nothing tells the handler what they did. - **A full framework** with decorators, classes and a dependency injection container: structured, but verbose, and tied to its own way of doing everything. With a minimal framework, the application also ends up coupled to it. Handlers take its request and response objects, middlewares follow its conventions, and errors go through its error handlers. Each framework does these differently, so moving to another one, or to another way of running the app, means rewriting the HTTP layer. Dotpress sits in between: the structure of a framework, with the syntax of plain functions and objects. It standardizes the HTTP layer and abstracts it from the server: - **one way to write your API**: the same routes, middlewares, errors and responses, whatever the HTTP framework underneath; - **the server is a choice you can change**: Express, Fastify or Hono, picked by an adapter, in one line; - **so is the way you run it**: a long-running Node.js instance or AWS Lambda for the API, and workers for the [events](https://dotpress.dev/services/events.md), with the same code. ## What you get - **Routes as declarations.** `defineRoute()` and `createRouteGroup()` take plain objects. Groups share a path prefix and middlewares, and nest. - **Validation and types from your schemas.** Zod schemas validate the path parameters, the query, the body, the uploaded files and the response. The handler receives the parsed values, typed. Path parameters are typed from the path itself. - **Errors are values.** A handler returns `notFoundError()` like any other value. Every error, from a failed validation to an unexpected exception, uses the same JSON format. - **Typed middlewares.** A middleware can guarantee a value to the handlers that use it, such as the authenticated user, and TypeScript knows it. - **Any HTTP server.** The core only relies on Web standards. The same app runs on Express, Fastify or Hono, on Node.js or AWS Lambda, with the same routing rules. - **Tested in memory.** The memory adapter runs requests without opening a port. - **Packages when you need them.** Authentication, OpenAPI documents, emails, events, cache and testing helpers, each in its own package, each optional. ## What Dotpress is not - **Not a full-stack framework.** No views, no ORM: use the database library you prefer. - **No dependency injection container.** Services are plain functions and objects, given to the app or exposed through the request context (see [Project structure](https://dotpress.dev/getting-started/project-structure.md)). - **Not on edge runtimes in 2.0.** The core is portable, but Dotpress 2.0 supports Node.js and AWS Lambda (see [the design decision](https://dotpress.dev/reference/design-decisions/edge.md)). ## Packages | Package | Purpose | | --------------------------- | ------------------------------------------------------------------------------------ | | `@dotpress/core` | Routes, validation, request pipeline, responses, errors, plugins | | `@dotpress/adapter-express` | Express 4 and 5 | | `@dotpress/adapter-fastify` | Fastify 5, on Node.js and AWS Lambda | | `@dotpress/adapter-hono` | Hono 4, on Node.js and AWS Lambda | | `@dotpress/auth` | JWT authentication: login, refresh token rotation, cookie sessions, typed `ctx.user` | | `@dotpress/openapi` | OpenAPI 3.1 documents from your routes, and a Scalar API reference | | `@dotpress/mailer` | Typed, multilingual email templates (MJML or HTML) | | `@dotpress/events` | Typed events and listeners, run by workers | | `@dotpress/cache` | Request memoization with batching, and a resilient cache | | `@dotpress/testing` | Memory adapter and assertions for tests | :::warning Beta Dotpress 2 is in beta (`2.0.0-beta`): the API is complete, and changes before 2.0.0 only from feedback, each change listed in the changelog. ::: :::tip Coming from v1 Dotpress 2 is a rewrite. `dotpress` is replaced by `@dotpress/core` and an adapter, and most options changed name. See [Migrate from v1](https://dotpress.dev/reference/migrate-from-v1.md). ::: --- url: https://dotpress.dev/getting-started/installation.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Installation ## Requirements - **Node.js 22.12 or later.** We recommend the current [LTS release](https://nodejs.org/en/about/previous-releases). Dotpress is tested on Node.js 22, 24 and 26. With Node.js 22.18 or later, Node.js runs TypeScript files directly, without a build step: the examples of this documentation use it. - **TypeScript 5.5 or later**, with `strict` enabled, as [Zod 4](https://zod.dev/#requirements) requires. The packages are tested with TypeScript 5.5, 6 and 7. - **Zod 4**, for the schemas. The packages are ES modules. A CommonJS project can still load them with `require()`, which Node.js 22.12 supports for ES modules. ## Install the core and an adapter Dotpress runs on the HTTP server of your choice: install the core, the adapter of your server, the server itself and Zod. ### Express ```sh [npm] npm install @dotpress/core @dotpress/adapter-express express zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-express npm:express npm:zod ``` ```sh [npm] npm install -D @types/express ``` ```sh [yarn] yarn add -D @types/express ``` ```sh [pnpm] pnpm add -D @types/express ``` ```sh [bun] bun add -D @types/express ``` ```sh [deno] deno add -D npm:@types/express ``` ### Fastify ```sh [npm] npm install @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-fastify npm:fastify npm:zod ``` ### Hono ```sh [npm] npm install @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-hono npm:hono npm:@hono/node-server npm:zod ``` Not sure which one to pick? Your routes do not depend on it, and you can switch later: see [Choosing an adapter](https://dotpress.dev/adapters/index.md). For AWS Lambda, see [the Lambda adapter](https://dotpress.dev/adapters/aws-lambda.md). ## Configure TypeScript Install TypeScript and the types of Node.js, which check your code (`tsc`, and your editor): ```sh [npm] npm install -D typescript @types/node ``` ```sh [yarn] yarn add -D typescript @types/node ``` ```sh [pnpm] pnpm add -D typescript @types/node ``` ```sh [bun] bun add -D typescript @types/node ``` ```sh [deno] deno add -D npm:typescript npm:@types/node ``` A configuration for Node.js 22.18 or later, which runs the `.ts` files directly: ```json title="tsconfig.json" { "compilerOptions": { "target": "ES2023", "lib": ["ES2023"], "module": "NodeNext", "moduleResolution": "NodeNext", "types": ["node"], "strict": true, "noEmit": true, "allowImportingTsExtensions": true, "erasableSyntaxOnly": true, "verbatimModuleSyntax": true, "skipLibCheck": true }, "include": ["src", "test"] } ``` Node.js only strips the types: `erasableSyntaxOnly` rejects the TypeScript syntax it cannot strip (enums, parameter properties), and relative imports end with `.ts`. Set `"type": "module"` in `package.json`. If you compile your code with `tsc` or a bundler instead, keep `strict: true` and use your usual settings. ## Add packages Each package is optional. Install it when you need it: | Need | Package | | ---------------------------------- | ----------------------------------------- | | Authentication | `@dotpress/auth@beta`, see the note below | | OpenAPI document and API reference | `@dotpress/openapi` | | Emails | `@dotpress/mailer` | | Events and workers | `@dotpress/events` | | Cache and memoization | `@dotpress/cache` | | Tests | `@dotpress/testing` (dev dependency) | :::warning @dotpress/auth during the beta Install `@dotpress/auth` with the `beta` tag. Without a tag, npm installs `@dotpress/auth` 1.x, the plugin of Dotpress 1. ::: ## Start from an example Each [example](https://dotpress.dev/examples/index.md) is a complete project, with its tests, that you can copy: ```sh npx degit dotpressjs/dotpress/examples/express my-api cd my-api npm install npm run dev ``` --- url: https://dotpress.dev/getting-started/quickstart.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Quickstart Build a small tasks API on Express in a few minutes: a first route, validated routes, a returned error, the API reference, and a test. ## 1. Create the project ```sh mkdir tasks-api && cd tasks-api npm init -y npm pkg set type=module ``` ```sh [npm] npm install @dotpress/core @dotpress/adapter-express express zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-express npm:express npm:zod ``` ```sh [npm] npm install -D typescript @types/node @types/express ``` ```sh [yarn] yarn add -D typescript @types/node @types/express ``` ```sh [pnpm] pnpm add -D typescript @types/node @types/express ``` ```sh [bun] bun add -D typescript @types/node @types/express ``` ```sh [deno] deno add -D npm:typescript npm:@types/node npm:@types/express ``` Then add the `tsconfig.json` of [Installation](https://dotpress.dev/getting-started/installation.md#configure-typescript). ## 2. Your first route ```ts title="src/server.ts" import { createApp, defineRoute } from '@dotpress/core' import { expressAdapter } from '@dotpress/adapter-express' defineRoute({ path: '/hello/:name', handler: ({ req }) => ({ message: `Hello, ${req.params.name}!` }), }) const app = await createApp({ adapter: expressAdapter() }) await app.listen(3000) ``` Run it, with Node.js 22.18 or later: ```sh node --watch src/server.ts ``` ```sh curl localhost:3000/hello/Ada # {"message":"Hello, Ada!"} ``` The handler returns a value: Dotpress sends it as JSON. `req.params.name` is typed `string`, from the path. ## 3. Validated routes Move the routes to their own file, and add a group of routes for the tasks. The schemas validate each request, and type it: ```ts title="src/routes.ts" import { createRouteGroup, defineRoute, notFoundError } from '@dotpress/core' import { z } from 'zod' defineRoute({ path: '/hello/:name', handler: ({ req }) => ({ message: `Hello, ${req.params.name}!` }), }) const Task = z.object({ id: z.uuid(), title: z.string(), done: z.boolean() }) type Task = z.infer const store = new Map() const tasks = createRouteGroup('/tasks') tasks.defineRoute({ method: 'post', path: '/', status: 201, schema: (z) => ({ body: z.object({ title: z.string().trim().min(1) }), response: Task, }), handler: ({ req }) => { const task = { id: crypto.randomUUID(), title: req.body.title, done: false } store.set(task.id, task) return task }, }) tasks.defineRoute({ path: '/:id', schema: () => ({ response: Task }), handler: ({ req }) => store.get(req.params.id) ?? notFoundError('Task not found'), }) ``` Hover `req.body` and `req.params`. Then import the routes in `src/server.ts`, before creating the app: ```ts title="src/server.ts" import { createApp } from '@dotpress/core' import { expressAdapter } from '@dotpress/adapter-express' import './routes.ts' const app = await createApp({ adapter: expressAdapter() }) await app.listen(3000) ``` An invalid body never reaches the handler: ```sh curl -X POST localhost:3000/tasks -H 'content-type: application/json' -d '{"title":""}' ``` ```json { "status": 400, "error": "VALIDATION_FAILED", "message": "Validation failed", "data": { "issues": [ { "source": "body", "path": ["title"], "code": "too_small", "message": "Too small: expected string to have >=1 characters" } ] } } ``` And an unknown task gets the error returned by the handler: ```sh curl localhost:3000/tasks/unknown # {"status":404,"error":"NOT_FOUND","message":"Task not found"} ``` ## 4. The API reference ```sh [npm] npm install @dotpress/openapi ``` ```sh [yarn] yarn add @dotpress/openapi ``` ```sh [pnpm] pnpm add @dotpress/openapi ``` ```sh [bun] bun add @dotpress/openapi ``` ```sh [deno] deno add npm:@dotpress/openapi ``` The OpenAPI plugin builds the document from your routes and schemas. Create the app in its own file, so that the tests can create it too: ```ts title="src/app.ts" import { createApp, type HttpAdapter } from '@dotpress/core' import { openapiPlugin } from '@dotpress/openapi' import './routes.ts' export const createTasksApp = (adapter: TAdapter) => createApp({ adapter, plugins: [openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0' } })], }) ``` ```ts title="src/server.ts" import { expressAdapter } from '@dotpress/adapter-express' import { createTasksApp } from './app.ts' const app = await createTasksApp(expressAdapter()) await app.listen(3000) ``` Open [localhost:3000/docs](http://localhost:3000/docs): every route is documented, with its parameters, body and responses. The document itself is served at `/openapi.json`. ## 5. A test ```sh [npm] npm install -D vitest @dotpress/testing ``` ```sh [yarn] yarn add -D vitest @dotpress/testing ``` ```sh [pnpm] pnpm add -D vitest @dotpress/testing ``` ```sh [bun] bun add -D vitest @dotpress/testing ``` ```sh [deno] deno add -D npm:vitest npm:@dotpress/testing ``` The memory adapter runs the requests in memory, without opening a port: the test uses the app as configured in production. ```ts title="test/tasks.test.ts" import { memoryAdapter } from '@dotpress/testing' import { expect, it } from 'vitest' import { createTasksApp } from '../src/app.ts' it('creates a task', async () => { const adapter = memoryAdapter() await createTasksApp(adapter) const res = await adapter.fetch( new Request('http://localhost/tasks', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'Write a test' }), }) ) expect(res.status).toBe(201) expect(await res.json()).toMatchObject({ title: 'Write a test', done: false }) }) ``` ```sh npx vitest run ``` ## Next steps - Understand [how Dotpress works](https://dotpress.dev/concepts/how-it-works.md), then the [request pipeline](https://dotpress.dev/concepts/request-pipeline.md). - Organize a growing app: [Project structure](https://dotpress.dev/getting-started/project-structure.md). - Go further with routes: [Route groups](https://dotpress.dev/routing/groups.md), [Validation](https://dotpress.dev/routing/validation.md), [Responses](https://dotpress.dev/routing/responses.md), [Middlewares](https://dotpress.dev/routing/middlewares.md). - See a complete project: the [Express example](https://dotpress.dev/examples/express.md). --- url: https://dotpress.dev/getting-started/project-structure.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Project structure Dotpress does not impose any folder layout. This page recommends one that scales, with its reasons, and when to adopt each step. Start small: a structure only pays off once the app needs it. ## Three steps | Step | Shape | Example | Move on when… | | -------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | 1. One file | Routes and server in `server.ts` | [Express](https://dotpress.dev/examples/express.md) | the file grows past a hundred lines | | 2. A few files | `config.ts`, `routes.ts`, `server.ts`, one file per service | [Events](https://dotpress.dev/examples/events.md), [Cache](https://dotpress.dev/examples/cache.md), [Mailer](https://dotpress.dev/examples/mailer.md) | several resources, or a second process (a worker) | | 3. By feature | `features/` on a shared base | [Tasks API](https://dotpress.dev/examples/tasks-api.md) | — | ## The structure by feature Business code is organized **by feature**, on a **shared base** for the infrastructure: ```text src/ config.ts configuration, validated by Zod at startup services/ creation of the services: functions, not singletons index.ts createRepositories(db), the type of the app services bus.ts event transport and bus mailer.ts mail provider and mailer http/ server.ts entry point: config → services → app → listen app.ts createApp(): plugins and routers routes.ts the routers of the features: the route table services-plugin.ts ctx.services, typed worker.ts entry point of the event worker db/ connection, schema or migrations features/ tasks/ routes.ts the router of the feature, its groups and middlewares schemas.ts Zod schemas shared by several routes repository.ts data access events.ts the events the feature emits mails/ the email templates of the feature notifications/ listeners.ts reactions to the events of other features test/ one file per behavior, and a support file ``` The [Tasks API example](https://dotpress.dev/examples/tasks-api.md) follows this structure. ## The principles ### A feature is a complete folder The routes, schemas, data access, events and email templates of a feature live together. Adding, changing or removing a feature touches one folder. The alternative, a folder per technical layer (`handlers/`, `events/`, `mails/`), works with three resources. With twenty, `handlers/` becomes a long flat list, and a single feature such as "assign a task" is spread over four folders. The shared base (configuration, services, HTTP, database) stays at the root: every feature uses it. :::tip Domain-driven design A feature is a vertical slice: it deliberately mixes routes, data access and templates. Teams practicing domain-driven design can map a feature to a bounded context, and split it inside (`domain/`, `application/`, `infrastructure/`). ::: ### Functions that create services, not singletons `services/` creates the services with functions (`createRepositories(db)`, `createTransport(config)`), called **once per entry point**: - the API, the worker and the scripts do not need the same services. Each creates its own, and closes them on shutdown; - each test creates its own services, in memory: no mocks of imported modules, no state leaking from one test to the next; - nothing connects to a database or a queue when a module is imported. ### Handlers find their services in `ctx` A small plugin of the app exposes its services in the request context, typed in every handler: ```ts title="src/http/services-plugin.ts" import { declareContextKey, definePlugin } from '@dotpress/core' interface AppServices { tasks: { findById(id: string): Promise<{ id: string; title: string } | undefined> } } declare module '@dotpress/core' { interface RequestContext { services: AppServices } } // Using ctx.services in an app without the plugin throws an explicit error. declareContextKey('services', 'servicesPlugin') export const servicesPlugin = (services: AppServices) => definePlugin({ name: 'services', setup(api) { api.decorateContext('services', () => services) }, }) ``` Route files become plain modules, and the app stays testable: each test creates the app with its own services. ```ts title="src/features/tasks/routes.ts" interface AppServices { tasks: { findById(id: string): Promise<{ id: string; title: string } | undefined> } } declare module '@dotpress/core' { interface RequestContext { services: AppServices } } import { createRouter, notFoundError } from '@dotpress/core' export const tasksRouter = createRouter() tasksRouter.defineRoute({ path: '/tasks/:id', handler: async ({ req, services }) => (await services.tasks.findById(req.params.id)) ?? notFoundError('Task not found'), }) ``` It is the mechanism of the Dotpress plugins (`ctx.user`, `ctx.mailer`, `ctx.cache`). Prefer one namespace (`ctx.services.tasks`) to flat keys: `ctx.users`, a repository, would be easy to confuse with `ctx.user`, the authenticated user. Two things to know about this typing: - **Module augmentation applies to the whole program**, not to one app: `ctx.services` is typed in every handler of the project. With one app per project, it makes no difference. - **It exists only if the module that declares it is part of the program.** Import a plugin where you register it, in `http/app.ts`, and its context keys are typed everywhere. ### Explicit routers `defineRoute()` and `createRouteGroup()` used on their own register the routes on a global router, which `createApp()` mounts by default. It suits a script or a small app, but the routes are registered by importing modules, and every app of the process gets all of them. As the app grows, each feature exports its own router, and `http/routes.ts` puts them together: ```ts title="src/http/routes.ts" import { projectsRouter } from '../features/projects/routes.ts' import { tasksRouter } from '../features/tasks/routes.ts' export const routers = [projectsRouter, tasksRouter] ``` ```ts title="src/http/app.ts" await createApp({ adapter, routers, plugins: [servicesPlugin(services)] }) ``` ### Events and listeners An event belongs to the feature that emits it (`features/tasks/events.ts`); a listener belongs to the feature that reacts (`features/notifications/listeners.ts`). Listeners are created with the services of the process that runs them: the worker in production. ### One entry point per process Each process has its file, which always does the same: configuration, services, app or worker, start, close on shutdown. In the Tasks API: `http/server.ts`, `worker.ts` and `seed.ts`. ### Tests by behavior One test file per behavior (a scenario, access rules, the cache…) rather than one per source file, and a `test/support.ts` that creates the app with in-memory services. ## When to split further - A `routes.ts` of several hundred lines: one file per route or per group in `handlers/`, assembled by `routes.ts`. - Schemas shared by several routes or by the tests: `schemas.ts`. - A feature that keeps growing: sub-features (`features/billing/invoices/`), or a domain-driven split inside. --- url: https://dotpress.dev/getting-started/ai-assistants.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # AI assistants AI assistants learned Dotpress 1 more than Dotpress 2: without the documentation, they tend to write code for the old API. This site gives them the documentation of Dotpress 2 in Markdown, a format they read better than web pages, following the [llms.txt](https://llmstxt.org) convention. ## The files | File | Content | Use it to | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | | [`/llms.txt`](https://dotpress.dev/llms.txt) | An index: the rules an assistant must know, then a link to each page, with a description | give an assistant the whole documentation: it reads the pages it needs | | [`/llms-full.txt`](https://dotpress.dev/llms-full.txt) | The whole documentation in one file | index the documentation in a tool. It is large: prefer the index for a conversation | | A `.md` URL for each page | The page in Markdown, such as [`/getting-started/installation.md`](https://dotpress.dev/getting-started/installation.md) | give one page. The menu of each page copies it, or opens it in an assistant | The files follow the documentation: they are rebuilt with the site, for the current version. ## Give the documentation to an assistant - **In a conversation**, give the URL of the index along with your request: "Read [https://dotpress.dev/llms.txt](https://dotpress.dev/llms.txt), then add a route that…". The assistant must be able to read web pages. - **In your editor**, if it can index a documentation site, add `https://dotpress.dev/llms.txt` or `https://dotpress.dev/llms-full.txt` to its sources. - **In your project**, write the rule in the instructions file that your assistant reads at the root of the repository (`AGENTS.md`, `CLAUDE.md`, or the file of your tool): ```md title="AGENTS.md" ## Dotpress This project uses Dotpress 2. Before writing Dotpress code, read https://dotpress.dev/llms.txt and the pages it links to. Do not use the API of Dotpress 1 (the `dotpress` package). ``` ## What to check in generated code - **The version.** Imports come from `@dotpress/core` and an adapter, never from `dotpress`. During the beta, `@dotpress/auth` is installed with the `beta` tag: without it, npm installs the plugin of Dotpress 1 (see [Installation](https://dotpress.dev/getting-started/installation.md)). - **Errors are returned.** A handler returns `notFoundError()`; it does not throw it (see [Returned errors](https://dotpress.dev/concepts/errors.md)). - **No generics.** Types come from the schemas and the path: `defineRoute<…>()` is a sign of an invented API (see [End-to-end typing](https://dotpress.dev/concepts/typing.md)). - **The tests.** An app is tested in memory, with `@dotpress/testing` (see [Testing](https://dotpress.dev/routing/testing.md)): ask the assistant for the tests of what it writes, and run them. --- url: https://dotpress.dev/concepts/how-it-works.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # How Dotpress works Dotpress separates what your API does from the server that runs it. ```text your code @dotpress/core adapter ┌──────────────────┐ ┌────────────────────────┐ ┌─────────────────┐ │ routes │ │ registry of the routes │ │ Express │ │ groups │ ─────► │ compiled into a │ ─────► │ Fastify │ │ middlewares │ │ request pipeline │ │ Hono │ │ plugins │ │ (Web standards only) │ │ AWS Lambda │ └──────────────────┘ └────────────────────────┘ └─────────────────┘ ``` ## Routes are declarations `defineRoute()` does not attach a function to a server: it records a declaration, made of a method, a path, schemas, middlewares and a handler. `createApp()` reads the declarations of its routers, checks them and compiles each route into a request pipeline. Because the routes are data before they are code: - **conflicts are detected at startup.** Two routes with the same method and path make `createApp()` throw, instead of one silently shadowing the other; - **the app can describe itself.** `app.routes` lists the mounted routes, and `@dotpress/openapi` builds the OpenAPI document from the same declarations: the documentation cannot drift from the code; - **the same routes run anywhere.** Nothing in a route depends on the HTTP server. ## Routers A router holds route declarations. `createRouter()` creates one, and `createApp({ routers })` mounts them: ```ts const tasksRouter = createRouter() tasksRouter.defineRoute({ path: '/tasks', handler: () => [] }) await createApp({ adapter, routers: [tasksRouter] }) ``` `defineRoute()` and `createRouteGroup()`, imported on their own, use the global router, which `createApp()` mounts when `routers` is omitted. Both styles are equivalent; explicit routers suit larger apps (see [Project structure](https://dotpress.dev/getting-started/project-structure.md#explicit-routers)). ## The app `createApp()` takes an adapter and the rest of the configuration, and returns the app: ```ts const app = await createApp({ adapter: expressAdapter(), routers: [tasksRouter], plugins: [openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0' } })], }) await app.listen(3000) // … await app.close() // waits for pending requests, then closes the plugins ``` Its lifecycle: 1. **`createApp()`** sets up the plugins, in the order of their dependencies, compiles the routes and runs the `onInit` hooks of the plugins. 2. Still in `createApp()`, the adapter mounts the routes on its server, then the `onReady` hooks run. 3. **`app.listen()`** starts the server. On AWS Lambda, the adapter receives the events instead. 4. Each request goes through the [request pipeline](https://dotpress.dev/concepts/request-pipeline.md). 5. **`app.close()`** stops the server, waits for the pending requests, and runs the `onClose` hooks of the plugins, in reverse order. ## Adapters An adapter connects the core to an HTTP server. On each request, it: 1. converts the native request into a standard one: method, path, headers, cookies, and the body, parsed by Dotpress according to its content type; 2. passes it to the core, which matches the route and runs its pipeline; 3. converts the response back, including streams and Server-Sent Events. Routing is done by Dotpress, not by the server. The rules are the same everywhere: matching is case-sensitive, static segments win over parameters whatever the declaration order, trailing slashes are ignored, and `HEAD` requests use the `GET` route. Every adapter passes the same conformance test suite. Your server stays available for what Dotpress does not do: each adapter accepts native middlewares (Express `helmet`, a Fastify plugin…), and `app.native()` returns the server instance. See [Adapters](https://dotpress.dev/adapters/index.md). ## Plugins A plugin extends the app from the outside: it adds routes, global middlewares, response filters and hooks, and can provide new keys of the request context, such as `ctx.user` for `@dotpress/auth`. The packages of Dotpress are plugins, and your app can have its own. See [Plugins](https://dotpress.dev/routing/plugins.md). --- url: https://dotpress.dev/concepts/request-pipeline.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Request pipeline Every request goes through the same steps, in the same order, on every adapter. ```text request │ ├─ adapter: parse the request (headers, cookies, body by content type) ├─ CORS preflight? ──────────────────────────────► 204 ├─ no matching route ────────────────────────────► 404, or 405 with Allow │ ├─ request ID and request logger ├─ onRequest hooks (plugins) ├─ global middlewares (plugins first, then createApp) ├─ group middlewares, outermost group first ├─ route middlewares ├─ request validation: params, query, body, files ► 400 VALIDATION_FAILED ├─ handler ├─ response validation (response schema) ├─ response filters (createApp and plugins, then router) │ ├─ CORS headers ├─ onResponse hooks (plugins) ▼ response ``` Any step can stop the pipeline with an error or a response: the following steps are skipped, and the response still gets its CORS headers and goes through the `onResponse` hooks. ## Middlewares run before validation Middlewares run **before** the request is validated. An unauthenticated request with an invalid body gets the `401` of the authentication middleware, not a `400`: the API does not reveal its validation rules to anonymous clients, and does not spend time validating requests it rejects anyway. As a consequence, a middleware sees the raw values received by the adapter (`ctx.req.params`, `query` and `body`, not yet parsed by the schemas), while the handler sees the validated values. A middleware returns nothing to continue, or an error or a response to stop the pipeline: ```ts const requireApiKey = defineMiddleware((ctx) => { if (ctx.req.header('x-api-key') !== apiKey) return unauthorizedError() }) ``` See [Middlewares and filters](https://dotpress.dev/routing/middlewares.md). ## The handler's value becomes the response The handler returns a value, and Dotpress builds the response: | The handler returns | Response | | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | a value | JSON, with the route `status` (`200` by default) | | nothing | `204 No Content`, or the route `status` | | an error (`notFoundError()`…) | the error, in the [standard format](https://dotpress.dev/concepts/errors.md) | | a response helper (`text()`, `redirect()`, `stream()`, `sse()`, `file()`…) | that response | JSON values are checked against the `response` schema, when the route has one, then go through the response filters. Raw responses (text, streams, files) skip both. ## Errors A step that throws or returns an error stops the pipeline: - an `HttpError` (`notFoundError()`, `forbiddenError()`…), thrown or returned, becomes its response; - anything else is unexpected: the error is logged with the request ID, passed to the `onError` hook, and the client gets a `500` without details (unless `exposeErrors` is enabled, in development). See [Returned errors](https://dotpress.dev/concepts/errors.md). ## Hooks Plugins can act around the pipeline: - **`onRequest`** runs before the middlewares, for the requests matching a route; - **`wrapRequest`** runs the whole pipeline of a request inside a function: request-scoped storage, tracing spans; - **`onResponse`** receives every response, including `404` and `405`, with the request, the request ID and the duration: request logging, metrics. It can replace the response. See [Logging and error hooks](https://dotpress.dev/routing/logging.md) and [Plugins](https://dotpress.dev/routing/plugins.md). --- url: https://dotpress.dev/concepts/context.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Request context Handlers and middlewares receive one argument: the context of the request, `ctx`. Destructure what you need: ```ts import { defineRoute } from '@dotpress/core' defineRoute({ path: '/reports/:id', handler: ({ req, res, logger, requestId }) => { logger.info({ reportId: req.params.id }, 'Report requested') res.setHeader('cache-control', 'no-store') return { id: req.params.id, requestId } }, }) ``` ## What it holds | Key | Content | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `req` | The request: `method`, `path`, `url`, typed `params`, `query`, `body` and `files`, `headers` (lowercase names), `cookies`, `ip`, `signal`, `header(name)` | | `res` | Response metadata: `setStatus()`, `setHeader()`, `appendHeader()`, `removeHeader()`, `setCookie()`, `clearCookie()` | | `requestId` | The ID of the request, also sent in the `X-Request-ID` header | | `logger` | A logger bound to the request: every line carries the request ID | | `raw` | The native request of the adapter (Express, Fastify, Hono, Lambda event), as an escape hatch | | `publicPath(path)` | The path of a route as seen by the browser, behind a proxy (see [base path](https://dotpress.dev/routing/http-options.md)) | `req` and `res` are the same on every adapter: a handler never touches the native request or response. It returns its value, and sets the status, headers and cookies on `res`. `req.signal` is aborted when the client disconnects: pass it to long operations (`fetch(url, { signal: req.signal })`). ## Keys added by plugins Plugins add their own keys to the context, typed: | Key | Plugin | | ----------------------- | -------------------------------------------------------- | | `ctx.user`, `ctx.auth` | `@dotpress/auth`: the authenticated user and their token | | `ctx.memo`, `ctx.cache` | `@dotpress/cache` | | `ctx.events` | `@dotpress/events` | | `ctx.mailer` | `@dotpress/mailer` | Keys provided with `decorateContext()` are computed on first access, at most once per request: a route that does not use the mailer does not pay for it. Using the key of a plugin that is not installed throws an explicit error, rather than returning `undefined`: ```text "ctx.mailer" is used, but the "mailerPlugin" plugin is not installed in createApp(). ``` ## Adding your own keys The context is extended with TypeScript module augmentation. A plugin provides the value, as in this plugin that exposes the services of the app: ```ts import { declareContextKey, definePlugin } from '@dotpress/core' interface AppServices { tasks: { findById(id: string): Promise<{ id: string } | undefined> } } declare module '@dotpress/core' { interface RequestContext { services: AppServices } } declareContextKey('services', 'servicesPlugin') export const servicesPlugin = (services: AppServices) => definePlugin({ name: 'services', setup(api) { api.decorateContext('services', () => services) }, }) ``` A middleware can also set a key for the request, such as the tenant of a multi-tenant API. Declare it optional, and let a [typed middleware](https://dotpress.dev/concepts/typing.md#middlewares-that-guarantee-a-value) guarantee it to the handlers. See [Project structure](https://dotpress.dev/getting-started/project-structure.md#handlers-find-their-services-in-ctx) for the pattern in a complete app. --- url: https://dotpress.dev/concepts/typing.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # End-to-end typing In Dotpress, you write types once, as schemas and paths, and TypeScript infers the rest. No generic to pass to `defineRoute()`, no interface to keep in sync with a validator. Every snippet of this page is compiled against Dotpress when the site is built: hover the code to see what your editor sees. ## Path parameters come from the path ```ts import { createRouteGroup } from '@dotpress/core' const projects = createRouteGroup('/orgs/:orgId/projects') projects.defineRoute({ path: '/:projectId/tasks/:taskId', handler: ({ req }) => req.params, }) ``` `req.params` is `{ orgId: string; projectId: string; taskId: string }`: the prefixes of the groups count, nested groups included. A typo such as `req.params.projectID` is a compile error. Give a `params` schema to validate or convert them: `params: z.object({ taskId: z.uuid() })`. ## Schemas type the request The handler receives the values parsed by the schemas: coerced, trimmed, with their defaults. ```ts import { defineRoute } from '@dotpress/core' defineRoute({ path: '/tasks', schema: (z) => ({ query: z.object({ page: z.coerce.number().int().min(1).default(1), done: z.stringbool().optional(), sort: z.enum(['date', 'title']).default('date'), }), }), handler: ({ req }) => { const { page, done, sort } = req.query return { page, done, sort } }, }) ``` A query string only carries strings: `z.coerce.number()` turns `?page=2` into `2`, and `z.stringbool()` turns `?done=true` into `true`. The same applies to `body` and to uploaded `files`. ## The response is checked With a `response` schema, the value returned by the handler must match it. A missing field is a compile error, before any test runs: ```ts import { defineRoute } from '@dotpress/core' defineRoute({ path: '/me', schema: (z) => ({ response: z.object({ id: z.string(), email: z.email() }), }), handler: () => ({ id: 'u_1' }), // Error: `email` is missing }) ``` At runtime, the response schema also validates and strips the value: a field that is not in the schema, such as a password hash, never reaches the client. Errors stay allowed: a handler with a `response` schema can still return `notFoundError()`. ## Middlewares that guarantee a value A middleware declared with `defineMiddleware<{ … }>()` tells TypeScript what it guarantees to the handlers that use it, directly or through a group. ```ts import { createRouteGroup, defineMiddleware, forbiddenError } from '@dotpress/core' interface Tenant { id: string plan: 'free' | 'pro' } declare const tenants: { byHost(host: string | undefined): Promise } declare module '@dotpress/core' { interface RequestContext { tenant?: Tenant } } const requireTenant = defineMiddleware<{ tenant: Tenant }>(async (ctx) => { ctx.tenant = await tenants.byHost(ctx.req.header('host')) if (!ctx.tenant) return forbiddenError('Unknown tenant') }) const settings = createRouteGroup('/settings', [requireTenant]) settings.defineRoute({ path: '/', handler: ({ tenant }) => ({ plan: tenant.plan }), }) ``` In the routes of the group, `tenant` is a `Tenant`, not `Tenant | undefined`: no non-null assertion, no repeated check. Elsewhere, it stays optional. ## The authenticated user `@dotpress/auth` works the same way. Describe your user once, and `requireAuth` guarantees it: ```ts import { defineRoute } from '@dotpress/core' import { requireAuth } from '@dotpress/auth' declare module '@dotpress/auth' { interface AuthUser { id: string email: string roles: string[] } } defineRoute({ path: '/profile', middlewares: [requireAuth], handler: ({ user }) => ({ email: user.email }), }) ``` See [Protecting routes](https://dotpress.dev/auth/protecting-routes.md). ## Handlers outside the route Declare the handler inside the route: TypeScript infers everything. A handler written apart, in its own file for instance, takes its type from `RouteHandler`, with the schema and the path parameters: ```ts import { defineRoute, type RouteHandler } from '@dotpress/core' import * as z from 'zod' const updateTaskSchema = { params: z.object({ id: z.uuid() }), body: z.object({ title: z.string().min(1) }), response: z.object({ id: z.string(), title: z.string() }), } const updateTask: RouteHandler = ({ req }) => ({ id: req.params.id, title: req.body.title, }) defineRoute({ method: 'put', path: '/tasks/:id', schema: updateTaskSchema, handler: updateTask }) ``` `HandlerContext` is the type of its context alone, for a function that receives it. Two more parameters exist, with defaults: `rawBody` (`true` for a route declared with `rawBody: true`), and the context provided by the middlewares (`ProvidedContext<[typeof requireAuth]>`). More often, keep the handler in the route, and move the business logic to a service that takes plain values. ## Context keys and services The keys added by plugins (`ctx.mailer`, `ctx.events`, `ctx.cache`) and by your app (`ctx.services`) are typed in every handler: your editor completes their methods and checks their arguments. A mail template, for instance, checks the data it receives. See [Request context](https://dotpress.dev/concepts/context.md). ## Where types stop Types describe what your code does; schemas check what clients send. Dotpress uses both: - **at compile time**, TypeScript checks your handlers against the types inferred from the schemas; - **at runtime**, the schemas validate every request, and the response when there is a `response` schema. A client can send anything: only the schemas protect the handler from it. Declare a schema for every input your handler reads. --- url: https://dotpress.dev/concepts/errors.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Returned errors In Dotpress, an error is a value: a handler or a middleware **returns** it, like any other result. ```ts import { defineRoute, conflictError, notFoundError } from '@dotpress/core' declare const invoices: { find(id: string): Promise<{ id: string; status: 'draft' | 'paid' } | undefined> markAsPaid(id: string): Promise<{ id: string; status: 'paid' }> } defineRoute({ method: 'post', path: '/invoices/:id/pay', handler: async ({ req }) => { const invoice = await invoices.find(req.params.id) if (!invoice) return notFoundError('Invoice not found') if (invoice.status === 'paid') return conflictError('Invoice already paid') return invoices.markAsPaid(invoice.id) }, }) ``` The control flow stays visible: every way out of the handler is a `return`, readable from top to bottom. There is no exception to catch elsewhere, and no error class to declare. ## One format for every error Every error response has the same shape, whoever produced it: your handler, a middleware, the validation, the router or an unexpected exception. ```json { "status": 404, "error": "NOT_FOUND", "message": "Invoice not found" } ``` | Field | Content | | --------- | ----------------------------------------------------------- | | `status` | The HTTP status, also the status of the response | | `error` | A stable code, for the clients to test | | `message` | A message for humans | | `data` | Optional details, such as the issues of a failed validation | Clients handle every error of the API with one piece of code. ## The helpers | Helper | Status | Code | | ------------------------ | ------ | ---------------------- | | `badRequestError()` | 400 | `BAD_REQUEST` | | `unauthorizedError()` | 401 | `UNAUTHORIZED` | | `forbiddenError()` | 403 | `FORBIDDEN` | | `notFoundError()` | 404 | `NOT_FOUND` | | `conflictError()` | 409 | `CONFLICT` | | `unprocessableError()` | 422 | `UNPROCESSABLE_ENTITY` | | `tooManyRequestsError()` | 429 | `TOO_MANY_REQUESTS` | | `internalError()` | 500 | `INTERNAL_ERROR` | Each takes an optional message, and options: `data`, details added to the body, and `cause`, the original error. For any other case, `errorResponse()` takes a status, a code, a message and the same options: ```ts return errorResponse(422, 'INVALID_TRANSITION', 'A paid invoice cannot be cancelled', { data: { status: 'paid' }, }) ``` ## Thrown errors work too Returning is the convention, but a thrown `HttpError` gives the same response, from a handler, a middleware or a helper of the routes. Services do not throw `HttpError`: they throw their own business errors, and the handler translates them into the HTTP error the client receives. See [Errors of your services](https://dotpress.dev/routing/errors.md#errors-of-your-services). ## Unexpected errors Anything else that is thrown, a bug or a database failure, is an unexpected error: - the client gets a `500 INTERNAL_ERROR`, without details, so that nothing internal leaks; - the error is logged with the request ID, and passed to the `onError` hook of the app and of the plugins, to report it (Sentry, for instance). In development, `createApp({ exposeErrors: true })` adds the message and the stack of the error to the `500` responses. Never enable it in production. See [Errors](https://dotpress.dev/routing/errors.md) for the errors produced by Dotpress itself (`404`, `405`, `413`…) and for error reporting, and [the design decision](https://dotpress.dev/reference/design-decisions/returned-errors.md) for the reasons behind this choice. --- url: https://dotpress.dev/concepts/options.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Options and durations Every Dotpress function that takes options follows the same rules. ## Unknown options are rejected A misspelled option would otherwise be ignored without a word: `middleware` instead of `middlewares`, and a route runs without its authentication. Dotpress throws a `TypeError` that names the option instead, when the app starts: ```ts defineRoute({ path: '/admin', middleware: [requireAuth], handler }) // TypeError: Route "/admin": unknown option "middleware". ``` This applies to `createApp()`, the routes (their `schema` and `meta` too), the error helpers, the console logger, the adapters and their Lambda handlers, OpenAPI, the test helpers, and the auth, mailer, events and cache services. TypeScript reports most of these mistakes first; the check catches the others, in JavaScript or with an object built at runtime. ## Durations An option typed `Duration` takes a number of **seconds**, fractions allowed, or a string with a unit: | Value | Duration | | ---------------- | ------------- | | `30`, `'30s'` | 30 seconds | | `0.5`, `'500ms'` | half a second | | `'10m'` | 10 minutes | | `'1h'` | 1 hour | | `'7d'` | 7 days | The units are `ms`, `s`, `m`, `h` and `d`, with no space and no combination (`'1h30m'` is refused). Negative numbers are refused too. The `Duration` type and `parseDuration()`, which converts a duration to milliseconds, are exported by `@dotpress/core`, for the options of your own code: ```ts import { parseDuration, type Duration } from '@dotpress/core' const timeout = (value: Duration) => parseDuration(value, 'options.timeout') timeout(1.5) // 1500 timeout('10m') // 600000 timeout('soon') // TypeError: options.timeout must be a number of seconds, or a duration like '500ms', '30s', '10m', '1h' or '7d'. ``` --- url: https://dotpress.dev/routing/routes.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Routes A route is declared with `defineRoute()`: a method, a path and a handler. The value returned by the handler is the response. ```ts import { defineRoute } from '@dotpress/core' declare const articles: { list(): Promise<{ id: string; title: string }[]> create(input: { title: string }): Promise<{ id: string; title: string }> } defineRoute({ path: '/articles', handler: () => articles.list(), }) defineRoute({ method: 'post', path: '/articles', status: 201, schema: (z) => ({ body: z.object({ title: z.string().min(1) }) }), handler: ({ req }) => articles.create(req.body), }) ``` ## The definition | Option | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `path` | The path, starting with `/`. Parameters start with `:` (`/articles/:id`). | | `method` | `get` (default), `post`, `put`, `patch`, `delete`, `head` or `options`. | | `handler` | Receives the [request context](https://dotpress.dev/concepts/context.md), returns the response. Can be `async`. | | `schema` | Zod schemas of the `params`, `query`, `body`, `files` and `response`: see [Validation](https://dotpress.dev/routing/validation.md). | | `middlewares` | Middlewares of the route: see [Middlewares](https://dotpress.dev/routing/middlewares.md). | | `status` | Success status: `200` by default, `204` when the handler returns nothing. | | `meta` | Documentation: `summary`, `description`, `tags`, other `responses`, `security`, `hidden`. Used by [OpenAPI](https://dotpress.dev/services/openapi.md). | | `bodyLimit` | Maximum body size of this route, in bytes: see [Bodies and file uploads](https://dotpress.dev/routing/bodies.md). | | `rawBody` | Keeps the raw bytes of the body in `req.rawBody`, to verify webhook signatures. | `schema` is a function that receives `z`, so that a route file does not even need to import Zod. A plain object works too: `schema: { body: TaskInput }`. ## Paths Paths contain static segments and `:param` segments only. Express wildcards, optional parameters and regular expressions are rejected at startup, so that a route behaves the same on every adapter. The rules of matching are the same on every adapter: - **Case-sensitive**: `/Articles` does not match `/articles`. - **Static segments first**: `/articles/latest` wins over `/articles/:id`, whatever the declaration order. - **Trailing slashes ignored**: `/articles/` matches `/articles`. - **Parameters are decoded**: `/tags/c%23` gives `req.params.tag === 'c#'`. - **`HEAD`** uses the `GET` route when there is no `HEAD` route, and never sends a body. Two routes with the same method and path, parameter names aside, make `createApp()` throw: a route can never shadow another silently. When the path exists for other methods only, the response is `405 Method Not Allowed`, with an `Allow` header listing them. Otherwise, `404 Not Found`. ## Routers `defineRoute()` registers the route on the **global router**, which `createApp()` mounts when no `routers` are given. The modules declaring routes must be imported before `createApp()`: ```ts import './routes/articles.ts' import './routes/authors.ts' const app = await createApp({ adapter }) ``` For a larger app, create **explicit routers** and give them to the app. Nothing is registered by importing a module, and a test can create an app with only some of the routers: ```ts import { createRouter } from '@dotpress/core' export const articlesRouter = createRouter() articlesRouter.defineRoute({ path: '/articles/:id', handler: ({ req }) => ({ id: req.params.id }), }) ``` ```ts const app = await createApp({ adapter, routers: [articlesRouter, authorsRouter] }) ``` A router has the methods of a group, `defineRoute()` and `createGroup()`, plus `addResponseFilter()`. See [Project structure](https://dotpress.dev/getting-started/project-structure.md#explicit-routers). ## Listing the routes `app.routes` lists the mounted routes, with their method, full path, schemas, metadata and security: useful to check a configuration, or to generate a client. :::tip Coming from v1 `defineRoute()` keeps the syntax of Dotpress 1. Handlers no longer receive the Express `req` and `res`: they return their value (see [Responses](https://dotpress.dev/routing/responses.md)), and path parameters are typed from the path, without `params: ['id']`. ::: --- url: https://dotpress.dev/routing/groups.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Route groups A group shares a path prefix and middlewares between routes. It organizes an API by resource (`/projects`), by audience (`/admin`) or by version (`/v2`). ```ts import { createRouteGroup, defineMiddleware, forbiddenError } from '@dotpress/core' declare const isAdmin: (ctx: unknown) => boolean const requireAdmin = defineMiddleware((ctx) => (isAdmin(ctx) ? undefined : forbiddenError())) const admin = createRouteGroup('/admin', [requireAdmin]) admin.defineRoute({ path: '/users', handler: () => [{ id: '1', name: 'Ada' }], }) ``` The route answers `GET /admin/users`, after `requireAdmin`. ## Nested groups A group creates sub-groups. The prefixes add up, and so do the middlewares, from the outermost group to the route: ```ts import { createRouteGroup, defineMiddleware } from '@dotpress/core' const requireAdmin = defineMiddleware(() => undefined) const requireBillingAccess = defineMiddleware(() => undefined) const admin = createRouteGroup('/admin', [requireAdmin]) const billing = admin.createGroup('/billing', [requireBillingAccess]) billing.defineRoute({ method: 'post', path: '/invoices', handler: () => ({ created: true }), }) ``` `POST /admin/billing/invoices` runs `requireAdmin`, then `requireBillingAccess`, then the route middlewares. ## Parameters in the prefix A prefix can hold parameters. Every route of the group receives them, typed: ```ts import { createRouteGroup } from '@dotpress/core' const projects = createRouteGroup('/projects/:projectId') const tasks = projects.createGroup('/tasks') tasks.defineRoute({ path: '/:taskId', handler: ({ req }) => req.params, }) ``` Hover `req.params`: `{ projectId: string; taskId: string }`. A member check written once on the `/projects/:projectId` group protects every route below it. ## Typed context A group with a [typed middleware](https://dotpress.dev/concepts/typing.md#middlewares-that-guarantee-a-value) passes its guarantee to all its routes, sub-groups included. With `requireAuth` on a group, `ctx.user` is defined in every route of the group: ```ts import { createRouteGroup } from '@dotpress/core' import { requireAuth } from '@dotpress/auth' declare module '@dotpress/auth' { interface AuthUser { id: string name: string } } const account = createRouteGroup('/account', [requireAuth]) account.defineRoute({ path: '/profile', handler: ({ user }) => ({ name: user.name }), }) ``` ## Groups of a router `createRouteGroup()` creates a group on the global router. With an [explicit router](https://dotpress.dev/routing/routes.md#routers), use `router.createGroup()`: ```ts import { createRouter } from '@dotpress/core' export const projectsRouter = createRouter() const projects = projectsRouter.createGroup('/projects') projects.defineRoute({ path: '/', handler: () => [] }) projects.defineRoute({ path: '/:projectId', handler: ({ req }) => req.params }) ``` A route at `path: '/'` answers the prefix itself: `GET /projects`. Prefixes start with `/`: to share middlewares without a prefix, give them to each route, or use a [global middleware](https://dotpress.dev/routing/middlewares.md#where-to-attach-them). See the [Tasks API example](https://dotpress.dev/examples/tasks-api.md) for nested groups with access checks. --- url: https://dotpress.dev/routing/validation.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Validation Any input of an API must be checked: it comes from clients you do not control. In Dotpress, each route declares the [Zod](https://zod.dev) schemas of its inputs, and the framework: - parses and validates the request before the handler runs; - answers `400` with every issue found, when the request is invalid; - gives the handler the parsed values, typed from the schemas. ```ts import { defineRoute } from '@dotpress/core' defineRoute({ method: 'post', path: '/members', schema: (z) => ({ body: z.object({ name: z.string().trim().min(1), age: z.number().int().min(13), location: z.string().optional(), }), }), handler: ({ req }) => ({ received: req.body }), }) ``` ## What can be validated | Schema | Validates | Typed as | | ---------- | ------------------------------------- | ------------------------------ | | `params` | Path parameters (strings) | `req.params` | | `query` | Query string | `req.query` | | `body` | Request body: JSON, form fields, text | `req.body` | | `files` | Uploaded files, `multipart/form-data` | `req.files` | | `response` | The value returned by the handler | the return type of the handler | ```ts import { defineRoute } from '@dotpress/core' defineRoute({ method: 'put', path: '/orgs/:orgId/users/:userId', schema: (z) => ({ params: z.object({ orgId: z.uuid(), userId: z.uuid() }), query: z.object({ notify: z.stringbool().default(false) }), body: z.object({ email: z.email(), name: z.string() }), }), handler: ({ req }) => ({ ...req.params, ...req.body, notify: req.query.notify }), }) ``` Without a `params` schema, path parameters are still typed, as strings, [from the path](https://dotpress.dev/concepts/typing.md#path-parameters-come-from-the-path). Without a `query` schema, `req.query` holds the raw strings (arrays for repeated keys); without a `body` schema, `req.body` is `unknown`: check it before use. ## When validation fails The request never reaches the handler. The client gets a `400` with every issue, each with its source: ```json { "status": 400, "error": "VALIDATION_FAILED", "message": "Validation failed", "data": { "issues": [ { "source": "query", "path": ["notify"], "code": "invalid_value", "message": "Invalid option: expected one of \"true\"|\"1\"|\"yes\"|\"on\"|\"y\"|\"enabled\"|\"false\"|\"0\"|\"no\"|\"off\"|\"n\"|\"disabled\"" }, { "source": "body", "path": ["age"], "code": "too_small", "message": "Too small: expected number to be >=13" } ] } } ``` The `code` and `message` of each issue come from Zod: a client can display them, or map the codes to its own messages. Validation runs after the [middlewares](https://dotpress.dev/routing/middlewares.md): a request rejected by the authentication middleware gets its `401`, whatever its body. ## Query strings and forms A query string only carries strings, and a key sent several times gives an array. Coerce the values with Zod: | Query | Schema | Value | | -------------- | --------------------- | --------------------------------------------------------------------- | | `?page=2` | `z.coerce.number()` | `2` | | `?done=true` | `z.stringbool()` | `true` (also `1`, `yes`, `on`; `false`, `0`, `no`, `off` for `false`) | | `?tag=a&tag=b` | `arrayOf(z.string())` | `['a', 'b']` | | `?tag=a` | `arrayOf(z.string())` | `['a']` | `arrayOf()`, from `@dotpress/core`, always gives an array, whether the key is sent once or several times: ```ts import { arrayOf, defineRoute } from '@dotpress/core' defineRoute({ path: '/articles', schema: (z) => ({ query: z.object({ tag: arrayOf(z.string()).default([]) }), }), handler: ({ req }) => ({ tags: req.query.tag }), }) ``` Nested keys such as `filter[status]=open` are not expanded into objects: the key is `filter[status]`. URL-encoded form bodies follow the same rules. ## Validating the response A `response` schema checks the value returned by the handler: ```ts import { defineRoute } from '@dotpress/core' import { z } from 'zod' declare const users: { find(id: string): Promise<{ id: string; email: string; passwordHash: string }> } const User = z.object({ id: z.string(), email: z.email() }) defineRoute({ path: '/users/:id', schema: () => ({ response: User }), handler: async ({ req }) => users.find(req.params.id), }) ``` - **At compile time**, the handler must return a value matching the schema, or an error. - **At runtime**, the value is parsed by the schema: fields that are not in it, such as `passwordHash` here, are removed. The response cannot leak them, even when the database returns more than expected. - A value that does not match is a bug of the API: the client gets a `500`, and the issues are logged. The response schema also documents the route in the [OpenAPI document](https://dotpress.dev/services/openapi.md). Give it an `id` with `.meta({ id: 'User' })` to declare it once in the document and reference it everywhere. A route that returns nothing answers `204 No Content`. A `response: z.never()` schema makes it explicit, and rejects any returned value. ## Tips - **Transform while you validate**: `.trim()`, `.toLowerCase()`, `.transform()` and defaults apply before the handler runs. The handler gets the clean value. - **Cross-field rules** go in `.refine()` or `.superRefine()` on the object schema. - **Reuse schemas**: declare them once in a module, and use them in several routes and in the tests. - **Prototype without schemas**, then add them: the types of the handler follow. :::tip Coming from v1 The `params: ['id']` shorthand is gone: path parameters are typed from the path. Validation errors now use the [standard error format](https://dotpress.dev/concepts/errors.md#one-format-for-every-error), with one flat list of issues. Dotpress 2 uses Zod 4. ::: --- url: https://dotpress.dev/routing/responses.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Responses A handler returns its response. It never writes to the native response object: Dotpress builds the response, on every adapter the same way. ## Return a value | The handler returns | Response | | ---------------------------------------- | ---------------------------------------------------------------------------- | | a value (object, array, string, number…) | `200` JSON, or the route `status` | | nothing (`undefined`) | `204 No Content`, or the route `status` | | an error (`notFoundError()`…) | the error, in the [standard format](https://dotpress.dev/concepts/errors.md) | | a response helper | the response it describes | ```ts import { defineRoute } from '@dotpress/core' declare const jobs: { enqueue(name: string): Promise<{ id: string }>; cancel(id: string): Promise } defineRoute({ method: 'post', path: '/jobs', status: 202, handler: () => jobs.enqueue('export'), }) defineRoute({ method: 'delete', path: '/jobs/:id', handler: async ({ req }) => { await jobs.cancel(req.params.id) }, }) ``` The first route answers `202` with the job as JSON; the second, `204` without body. ## Status, headers and cookies `ctx.res` sets the metadata of the response, whatever the handler returns: ```ts import { defineRoute } from '@dotpress/core' declare const createSession: () => Promise<{ id: string; token: string }> defineRoute({ method: 'post', path: '/sessions', handler: async ({ res }) => { const session = await createSession() res .setStatus(201) .setHeader('cache-control', 'no-store') .setCookie('session', session.token, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 24, }) return { id: session.id } }, }) ``` | Method | Effect | | --------------------------------- | ------------------------------------------------------------- | | `setStatus(status)` | Status of the response | | `setHeader(name, value)` | Sets a header, replacing its value | | `appendHeader(name, value)` | Adds a value to a header | | `removeHeader(name)` | Removes a header | | `setCookie(name, value, options)` | Adds a `Set-Cookie` header | | `clearCookie(name, options)` | Expires a cookie: use the `path` and `domain` it was set with | Headers and cookies are kept on error responses returned or thrown as `HttpError`, and dropped on unexpected errors (`500`). :::warning Cookie security `setCookie()` only applies the options you give, with `path: '/'` by default. For a session or any secret, set `httpOnly: true` (out of reach of the JavaScript of the page), `secure: true` (HTTPS only) and `sameSite`. For authentication, prefer the [cookie mode of `@dotpress/auth`](https://dotpress.dev/auth/cookies.md), which sets them for you. ::: Request cookies are parsed: `ctx.req.cookies.session`. ## Response helpers For anything other than plain JSON, return a helper from `@dotpress/core`: ```ts return json(data, { status: 201, headers: { location: '/members/1' } }) return text('OK') return redirect('/login') // 302 return redirect('/new', { status: 301 }) // or 303, 307, 308 return file(bytes, { filename: 'invoice.pdf', contentType: 'application/pdf' }) return stream(source, { contentType: 'text/csv' }) return sse(source) return empty({ status: 202 }) ``` | Helper | Response | | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `json(data, init)` | JSON with a status and headers. Still validated by the `response` schema and filtered. | | `text(body, init)` | `text/plain; charset=utf-8`, or the `content-type` of `init.headers` (HTML, CSV…) | | `redirect(location, { status?, headers? })` | A redirect, `302` by default | | `file(body, init)` | A download: `Uint8Array`, `ArrayBuffer`, `Blob` or `ReadableStream`, with a `filename` and `disposition` (`attachment` or `inline`) | | `stream(source, init)` | A streamed body | | `sse(source, init)` | Server-Sent Events | | `empty(init)` | No body: `204` by default | Responses other than `json()` skip the `response` schema and the response filters. Redirects are not prefixed with the [base path](https://dotpress.dev/routing/http-options.md#base-path) of the app: use `ctx.publicPath('/login')` to redirect to a route of the app behind a proxy. ## Streams `stream()` sends the body as it is produced. The source is a `ReadableStream`, an iterable, an async iterable, or a function returning one: typically an async generator, which receives the abort signal of the request. ```ts import { defineRoute, stream } from '@dotpress/core' declare const orders: { export(options: { signal: AbortSignal }): AsyncIterable<{ id: string; total: number }> } defineRoute({ path: '/orders/export', handler: () => stream( async function* ({ signal }) { yield 'id,total\n' for await (const order of orders.export({ signal })) { yield `${order.id},${order.total}\n` } }, { contentType: 'text/csv' } ), }) ``` When the client disconnects, the signal is aborted and the generator stops: its `finally` blocks run, so the database cursor is released. ## Server-Sent Events `sse()` sends events to the browser, which reads them with `EventSource`. Each event is a string, or an object with `data` (sent as JSON when it is not a string), `event`, `id`, `retry` or `comment`: ```ts import { defineRoute, sse } from '@dotpress/core' declare const notifications: { watch(options: { signal: AbortSignal }): AsyncIterable<{ id: string; text: string }> } defineRoute({ path: '/notifications/live', handler: () => sse(async function* ({ signal }) { for await (const notification of notifications.watch({ signal })) { yield { event: 'notification', id: notification.id, data: notification } } }), }) ``` A comment is sent every 15 seconds to keep the connection open through proxies (`heartbeat` option, `false` to disable it). An error raised by a stream after the response has started is logged and reported to `onError`, and the connection is closed: the status was already sent. ## Client disconnections `ctx.req.signal` is aborted when the client goes away. Pass it to long operations, so that they stop instead of working for nobody: ```ts handler: async ({ req }) => { const report = await fetch(reportServiceUrl, { signal: req.signal }) return report.json() } ``` :::tip Coming from v1 Handlers no longer receive the Express `res`: return the value, and use `ctx.res` for the status, headers and cookies. Returning nothing now always answers `204`. ::: --- url: https://dotpress.dev/routing/errors.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Errors Handlers and middlewares return their errors, built with the helpers of `@dotpress/core`. This page lists them, the errors Dotpress produces itself, and how to report the unexpected ones. For the principles, see [Returned errors](https://dotpress.dev/concepts/errors.md). ## Returning an error ```ts import { defineRoute, forbiddenError, notFoundError } from '@dotpress/core' declare const documents: { find(id: string): Promise<{ id: string; ownerId: string } | undefined> } declare module '@dotpress/core' { interface RequestContext { userId?: string } } defineRoute({ path: '/documents/:id', handler: async ({ req, userId }) => { const document = await documents.find(req.params.id) if (!document) return notFoundError('Document not found') if (document.ownerId !== userId) return forbiddenError() return document }, }) ``` | Helper | Status | `error` | | ------------------------------------------ | ------ | ---------------------- | | `badRequestError(message?, options?)` | 400 | `BAD_REQUEST` | | `unauthorizedError(message?, options?)` | 401 | `UNAUTHORIZED` | | `forbiddenError(message?, options?)` | 403 | `FORBIDDEN` | | `notFoundError(message?, options?)` | 404 | `NOT_FOUND` | | `conflictError(message?, options?)` | 409 | `CONFLICT` | | `unprocessableError(message?, options?)` | 422 | `UNPROCESSABLE_ENTITY` | | `tooManyRequestsError(message?, options?)` | 429 | `TOO_MANY_REQUESTS` | | `internalError(message?, options?)` | 500 | `INTERNAL_ERROR` | Without a message, each uses the standard reason phrase (`Not Found`). The options are `data`, details added to the body, and `cause`, the original error, kept for the logs and never sent: ```ts return notFoundError('Member not found', { data: { id: req.params.id } }) ``` ## Custom errors `errorResponse(status, code, message, options?)` builds any other error. Use stable codes: clients test them. ```ts return errorResponse(422, 'INVALID_STATE', 'Invalid state transition', { data: { state: 'archived', previousState: 'pending' }, }) ``` ```json { "status": 422, "error": "INVALID_STATE", "message": "Invalid state transition", "data": { "state": "archived", "previousState": "pending" } } ``` `data` is sent to the client: never put internal details in it. All helpers return an `HttpError`, which a handler or a middleware can also throw, with the same result. `isHttpError(value)` recognizes one. ## Errors of your services HTTP errors belong to the routes. A service never throws an `HttpError`: it returns `undefined` when nothing is found, and throws its own error when a business rule is broken. The handler translates it: ```ts // services/invoices.ts export class InvoiceAlreadyPaidError extends Error {} export const payInvoice = async (id: string) => { const invoice = await db.invoices.find(id) if (!invoice) return undefined if (invoice.paidAt) throw new InvoiceAlreadyPaidError(id) return db.invoices.update(id, { paidAt: new Date() }) } // routes/invoices.ts handler: async ({ req }) => { try { return (await payInvoice(req.params.id)) ?? notFoundError('Invoice not found') } catch (error) { if (error instanceof InvoiceAlreadyPaidError) return conflictError('Invoice already paid') throw error // anything else: 500, reported by onError } } ``` When several routes call the same service, share the translation in a function of the feature: ```ts const toHttpError = (error: unknown) => { if (error instanceof InvoiceAlreadyPaidError) return conflictError('Invoice already paid') if (error instanceof InvoiceCancelledError) return unprocessableError('Invoice cancelled') throw error } handler: ({ req }) => payInvoice(req.params.id).catch(toHttpError) ``` The service stays usable from a worker or a script, and the client only receives messages written for it. A business error left untranslated is a `500`, without details: a forgotten case shows up in `onError`, not in the response. See [the design decision](https://dotpress.dev/reference/design-decisions/returned-errors.md#business-errors-and-http-errors). ## Errors produced by Dotpress | Status | `error` | When | | ------ | ------------------------ | ------------------------------------------------------------------------------------------ | | 400 | `VALIDATION_FAILED` | The request does not match the schemas of the route. `data.issues` lists the issues. | | 400 | `MALFORMED_BODY` | The body cannot be parsed: invalid JSON, UTF-8 or multipart. | | 404 | `NOT_FOUND` | No route matches the path (`Route not found`). | | 405 | `METHOD_NOT_ALLOWED` | The path exists, for other methods only. The `Allow` header lists them. | | 413 | `PAYLOAD_TOO_LARGE` | The body exceeds the [body limit](https://dotpress.dev/routing/bodies.md#body-size-limit). | | 415 | `UNSUPPORTED_MEDIA_TYPE` | Compressed body (`Content-Encoding`), or unknown charset. | | 500 | `INTERNAL_ERROR` | An unexpected error (see below). | These responses use the standard format too, and get the CORS headers: a browser client can read them. ## Unexpected errors An exception that is not an `HttpError` is unexpected: a bug, a database failure, a timeout. Dotpress: 1. logs it with the request logger, so the log line carries the request ID; 2. passes it to the `onError` hooks; 3. answers `500 INTERNAL_ERROR`, without any detail: an exception message can reveal a query, a path or a secret. The response carries the `X-Request-ID` header: a client reporting a problem gives it, and you find the log line. ### Reporting errors `onError` receives every unexpected error, with the request context (`undefined` when the error happened outside a route): ```ts import * as Sentry from '@sentry/node' const app = await createApp({ adapter, onError: (error, ctx) => { Sentry.captureException(error, { tags: { requestId: ctx?.requestId } }) }, }) ``` Plugins add their own hooks with `api.onError()`. A failing hook is logged, and never changes the response. ### Details in development `exposeErrors: true` adds the `name`, `message` and `stack` of the error to the `data` of `500` responses, and the issues when a response does not match its schema: ```ts const app = await createApp({ adapter, exposeErrors: config.env === 'development' }) ``` :::danger Never enable `exposeErrors` in production. Dotpress never reads `NODE_ENV` or any environment variable itself: the decision is yours, explicit. ::: ## Errors of native middlewares Errors passed to `next(error)` by native Express middlewares are converted to the standard format: a client error (a `status` from 400 to 499) keeps its status, anything else is a `500` reported to `onError`. :::tip Coming from v1 `isDev` is replaced by `exposeErrors`, and `onException` by `onError`. A thrown `HttpError` now gives the same response as a returned one (Dotpress 1 answered `500`), and the `404` and `500` produced by the framework use the standard format. ::: --- url: https://dotpress.dev/routing/middlewares.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Middlewares and filters A middleware runs before the handler: to authenticate, check a permission, resolve a tenant, rate-limit. A response filter runs after it, to transform the returned value. ## Middlewares A middleware is a function of the request context. It returns nothing to let the request continue, or an error (or a response) to stop it: ```ts import { defineMiddleware, unauthorizedError } from '@dotpress/core' declare const apiKeys: { isValid(key: string | undefined): Promise } const requireApiKey = defineMiddleware(async (ctx) => { if (!(await apiKeys.isValid(ctx.req.header('x-api-key')))) { return unauthorizedError('Invalid API key') } }) ``` | A middleware returns | Effect | | ------------------------------------------- | ---------------------------------------------- | | nothing | The next middleware runs, then the handler | | an error (`HttpError`) | The pipeline stops: the error is the response | | a response helper (`redirect()`, `json()`…) | The pipeline stops: the helper is the response | Any other value is a bug, answered with a `500`. A thrown error stops the pipeline like a returned one. `defineMiddleware()` only adds types; a plain function `(ctx) => …` is a middleware too. ## Where to attach them ```ts // Every route of the app await createApp({ adapter, middlewares: [requestTimeout] }) // Every route of a group, and of its sub-groups const admin = createRouteGroup('/admin', [requireAdmin]) // One route defineRoute({ path: '/reports', middlewares: [requireApiKey], handler }) ``` For a request, they run in this order: 1. the global middlewares added by plugins (`@dotpress/auth` reads the token there); 2. the global middlewares of `createApp()`; 3. the middlewares of the groups, outermost first; 4. the middlewares of the route, in order. Then the request is validated, and the handler runs. ## Middlewares see the raw request Middlewares run **before** validation (see [Request pipeline](https://dotpress.dev/concepts/request-pipeline.md#middlewares-run-before-validation)): `ctx.req.params`, `query` and `body` hold the values received, not yet parsed by the schemas. A middleware that reads them checks them itself. ## Middlewares that guarantee a value A middleware can set a context key and guarantee it to the handlers. Declare the key optional with module augmentation, and the guarantee with the type parameter of `defineMiddleware()`: ```ts import { defineMiddleware, forbiddenError } from '@dotpress/core' interface Workspace { id: string name: string } declare const workspaces: { find(id: string | undefined): Promise } declare module '@dotpress/core' { interface RequestContext { workspace?: Workspace } } const requireWorkspace = defineMiddleware<{ workspace: Workspace }>(async (ctx) => { ctx.workspace = await workspaces.find(ctx.req.header('x-workspace-id')) if (!ctx.workspace) return forbiddenError('Unknown workspace') }) ``` In the routes using `requireWorkspace`, directly or through a group, `ctx.workspace` is a `Workspace`. See [End-to-end typing](https://dotpress.dev/concepts/typing.md#middlewares-that-guarantee-a-value). ## Documenting the security A middleware that checks credentials can declare the security scheme it accepts. The [OpenAPI document](https://dotpress.dev/services/openapi.md) then marks the routes using it as secured: ```ts const requireApiKey = defineMiddleware(checkApiKey, { security: ['apiKey'] }) ``` `requireAuth` and `requireRole()` of `@dotpress/auth` declare `bearerAuth`. ## Native middlewares of your server Middlewares of the ecosystem of your server (`helmet`, `compression`, a Fastify plugin, a Hono middleware) still work: register them through the `beforeRoutes` option of the adapter. They run before Dotpress, and do not know about the route. ```ts import helmet from 'helmet' const app = await createApp({ adapter: expressAdapter({ beforeRoutes: (app) => { app.use(helmet()) }, }), }) ``` Prefer Dotpress middlewares for the logic of your API: they run on every adapter, see the matched route and the typed context, and can be tested in memory. See [Adapters](https://dotpress.dev/adapters/index.md). ## Response filters A response filter receives the value returned by a handler, and returns the value to send. Use it to wrap every response in an envelope, or to add metadata: ```ts import { createRouter } from '@dotpress/core' const api = createRouter() api.addResponseFilter((ctx, result) => ({ data: result, meta: { requestId: ctx.requestId }, })) ``` | Registered with | Applies to | | -------------------------------------- | ---------------------------------------------------------- | | `createApp({ responseFilters })` | every route of the app | | `api.addResponseFilter()`, in a plugin | every route of the app, after the filters of `createApp()` | | `router.addResponseFilter()` | the routes of the router, after the filters above | | `addResponseFilter()` | the routes of the global router | Filters can be `async`. They run after the `response` schema has validated the value, and only for JSON results: errors, `text()`, `stream()`, `file()` and the other raw responses are sent as they are. ## Before and after the handler A middleware only runs before the handler. To measure a request, log it, or run it in a context (tracing, request-scoped storage), write a plugin with the `onResponse` or `wrapRequest` hook. See [Logging and error hooks](https://dotpress.dev/routing/logging.md). :::tip Coming from v1 Middlewares now run before validation, and can be attached to groups. Their return value is checked: nothing, an error or a response. The Express hooks `useBeforeRoutes` and `useAfterRoutes` moved to the options of the Express adapter (`beforeRoutes`, `afterRoutes`). ::: --- url: https://dotpress.dev/routing/bodies.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Bodies and file uploads Dotpress reads and parses request bodies itself, the same way on every adapter. Validate them with the `body` and `files` schemas of the route (see [Validation](https://dotpress.dev/routing/validation.md)). ## Content types | `Content-Type` | `req.body` | | ----------------------------------- | -------------------------------------------------------------- | | `application/json`, `*+json` | the parsed JSON | | `application/x-www-form-urlencoded` | a record of strings, arrays for repeated keys | | `multipart/form-data` | the text fields, like a form; the files are in `req.files` | | `text/*` | a string, decoded with the declared charset (UTF-8 by default) | | anything else | the bytes, as a `Uint8Array` | | no body | `undefined` | A body that cannot be parsed (invalid JSON, invalid UTF-8, broken multipart) gets `400 MALFORMED_BODY`. A compressed body (`Content-Encoding: gzip`…) or an unknown charset gets `415 UNSUPPORTED_MEDIA_TYPE`. ## Body size limit Bodies are limited to **1 MiB** by default. A larger body gets `413 PAYLOAD_TOO_LARGE`: reading stops as soon as the declared length, or the bytes read, exceed the limit. Change the limit for the whole app with the `bodyLimit` option of the adapter, or for one route with its own `bodyLimit`: ```ts const app = await createApp({ adapter: expressAdapter({ bodyLimit: 256 * 1024 }) }) defineRoute({ method: 'post', path: '/imports', bodyLimit: 20 * 1024 * 1024, // 20 MiB, for this route only handler, }) ``` Keep the default limit low, and raise it only on the routes that need it: a large limit everywhere lets any client make the server read large bodies. ## File uploads `multipart/form-data` bodies are parsed by Dotpress, on every adapter, without Multer or another dependency. Files are Web [`File`](https://developer.mozilla.org/docs/Web/API/File) objects, validated by the `files` schema with Zod: ```ts import { defineRoute } from '@dotpress/core' declare const storage: { put(key: string, bytes: Uint8Array, type: string): Promise } defineRoute({ method: 'post', path: '/profile/avatar', bodyLimit: 3 * 1024 * 1024, schema: (z) => ({ files: z.object({ avatar: z.file().max(2 * 1024 * 1024).mime(['image/png', 'image/jpeg']), }), body: z.object({ alt: z.string().max(200).optional() }), }), handler: async ({ req }) => { const { avatar } = req.files const bytes = new Uint8Array(await avatar.arrayBuffer()) const url = await storage.put(`avatars/${crypto.randomUUID()}`, bytes, avatar.type) return { url, alt: req.body.alt } }, }) ``` - `req.files.avatar` is a `File`: `name`, `type`, `size`, `arrayBuffer()`, `stream()`, `text()`. - The text fields of the form are in `req.body`, validated by the `body` schema. - An invalid file gets the standard `400 VALIDATION_FAILED`, with `source: 'files'` issues. - Files count toward the body limit: raise `bodyLimit` on upload routes. - Files are kept in memory: for very large files, upload them directly to object storage (a presigned URL) rather than through the API. :::warning Check what you accept The `type` of a file and its name are sent by the client: they can lie. Limit the size and the types with the schema, generate the storage name yourself, and never serve uploaded files from the domain of your app without a `Content-Type` you control. ::: ### Several files A field sent several times gives an array. `arrayOf()` always gives an array, whether the field is sent once or several times: ```ts import { arrayOf, defineRoute } from '@dotpress/core' defineRoute({ method: 'post', path: '/albums/:id/photos', bodyLimit: 50 * 1024 * 1024, schema: (z) => ({ files: z.object({ photos: arrayOf(z.array(z.file().mime(['image/jpeg'])).max(10)), }), }), handler: ({ req }) => ({ count: req.files.photos.length }), }) ``` ## Raw bodies for webhooks Webhook providers sign the exact bytes they send. Declare `rawBody: true` to receive them in `req.rawBody`, in addition to the parsed `req.body`: ```ts import { defineRoute, unauthorizedError } from '@dotpress/core' declare const verifySignature: (payload: Uint8Array, signature: string | undefined) => Promise defineRoute({ method: 'post', path: '/webhooks/payments', rawBody: true, schema: (z) => ({ body: z.object({ type: z.string(), id: z.string() }) }), handler: async ({ req }) => { if (!(await verifySignature(req.rawBody, req.header('x-signature')))) { return unauthorizedError('Invalid signature') } return { received: req.body.id } }, }) ``` `req.rawBody` is a `Uint8Array`, typed only on routes declared with `rawBody: true`. With Express, do not register a native body parser (`express.json()`) for these routes: the adapter must read the body itself. :::tip Coming from v1 Multer is no longer used: the `files` option and `getFile()` are replaced by a `files` schema and `req.files`, with Web `File` objects. The default body limit is 1 MiB (Dotpress 1: 100 KB). ::: --- url: https://dotpress.dev/routing/http-options.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # CORS, cookies and base path These options of `createApp()` adapt the API to where it runs: browsers on other origins, cookies, a reverse proxy. ## CORS Browsers block the requests of a page to an API on another origin, unless the API allows them (Cross-Origin Resource Sharing). CORS is **disabled by default**: enable it with the origins you trust. ```ts const app = await createApp({ adapter, cors: { origin: ['https://app.example.com', /^https:\/\/[a-z]+\.example\.com$/], credentials: true, // cookies, fetch(…, { credentials: 'include' }) exposedHeaders: ['x-request-id'], maxAge: 600, // preflight cache, in seconds }, }) ``` | Option | Description | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `origin` | Required. `'*'` (any origin, without credentials), an origin (lowercase, without trailing slash), a regular expression, a list of them, or a function `(origin, request) => boolean`, which can be async. | | `credentials` | Allows cookies and credentialed requests. Cannot be combined with `'*'`. `false` by default. | | `allowedHeaders` | Request headers allowed by preflight responses. By default, those the browser asks for. | | `exposedHeaders` | Response headers the browser may read, besides the safelisted ones. None by default. | | `maxAge` | How long browsers may cache a preflight response, in seconds. | - **Preflight requests** from an allowed origin get a `204` listing the methods of the routes of the path, before any middleware: authentication does not block them. - **Every response** to an allowed origin gets the CORS headers, errors included, so that the client can read a `401` or a `422`. - **Other origins** get responses without CORS headers: the browser blocks them. CORS is not an access control: the server still answers, and authentication protects the routes. - `Vary: Origin` is added to every response, unless `origin` is `'*'`, so that caches do not mix origins. - An `origin` function that throws is logged, and refuses the origin. - The CORS headers are added before the `onResponse` hooks, which see the final response. - Native routes of the HTTP server (registered in `beforeRoutes`, for instance) are not covered: configure CORS on the server for them. :::warning List the origins you trust explicitly. A function that accepts any origin, combined with `credentials: true`, lets any website make requests with the cookies of your users. ::: With `@dotpress/auth` in cookie mode, the origins allowed with credentials are also trusted by its protection against cross-site request forgery (see [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md)). Behind API Gateway or a Lambda Function URL, configure CORS either in AWS or in Dotpress, not both: AWS answers preflight requests before the function runs. ## Cookies Request cookies are parsed on every request, without a dependency: ```ts handler: ({ req }) => ({ theme: req.cookies.theme ?? 'light' }) ``` Set them with `ctx.res.setCookie(name, value, options)` and remove them with `clearCookie()`. The options are those of the `Set-Cookie` header: `maxAge`, `expires`, `path` (`/` by default), `domain`, `secure`, `httpOnly`, `sameSite`, `partitioned`, `priority`. No security option is applied for you: set `httpOnly`, `secure` and `sameSite` for every cookie holding a session or a secret. See [Responses](https://dotpress.dev/routing/responses.md#status-headers-and-cookies). ## Base path To serve the API under a sub-path, for instance `https://example.com/my-app/api/users` behind a reverse proxy shared by several apps, use one of these options, depending on what the proxy forwards: ```ts // The proxy forwards the full path (nginx: proxy_pass http://app;) await createApp({ adapter, basePath: '/my-app/api' }) // The proxy removes the prefix (nginx: proxy_pass http://app/;, Traefik: stripPrefix) await createApp({ adapter, publicBasePath: '/my-app/api' }) ``` - **`basePath`** prefixes every route, plugin routes included: `GET /users` is served at `/my-app/api/users`, and other paths get a `404`. `ctx.req.path` and `app.routes` hold the full paths. - **`publicBasePath`** does not change the routing. It changes the paths seen by the browser: the paths of the cookies set by plugins, the URLs of the API reference, and the paths built with `publicPath()`. The two options cannot be combined. `ctx.publicPath()`, `app.publicPath()` and `api.publicPath()` (in plugins) give the browser path of a route path. Redirects are not prefixed automatically, since they may target a page outside of the API: ```ts defineRoute({ path: '/old', handler: (ctx) => redirect(ctx.publicPath('/new')), // Location: /my-app/api/new }) ``` ## Client IP address behind a proxy `ctx.req.ip` is the address of the client as seen by the HTTP server. Behind a load balancer or a reverse proxy, it is the address of the proxy, unless the server trusts the proxy headers (`X-Forwarded-For`): configure it on the server, for instance the `trust proxy` setting of Express, or the `trustProxy` option of Fastify. Only trust the proxies you run: a client can send any `X-Forwarded-For` header. The login throttling of `@dotpress/auth` uses this address: see [Passwords and brute force](https://dotpress.dev/auth/passwords.md). --- url: https://dotpress.dev/routing/logging.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Logging and error hooks Dotpress logs through one logger, given to the app, and gives each request a logger of its own, bound to its request ID. ## The logger By default, the app logs to the console, from the `info` level. Pass your logger to `createApp()`: ```ts import pino from 'pino' const app = await createApp({ adapter, logger: pino() }) ``` The `Logger` interface is the one of [Pino](https://getpino.io): a Pino instance works as is. Any logger with `debug`, `info`, `warn`, `error` and `child()` methods, accepting `(message)` or `(data, message)`, works too. The default logger can be configured: ```ts import { createConsoleLogger } from '@dotpress/core' const logger = createConsoleLogger({ level: 'debug', bindings: { service: 'billing-api' } }) ``` ## The request logger `ctx.logger` is a child logger: every line it writes carries the `requestId` of the request. ```ts import { defineRoute } from '@dotpress/core' declare const payments: { refund(id: string): Promise<{ amount: number }> } defineRoute({ method: 'post', path: '/payments/:id/refund', handler: async ({ req, logger }) => { const refund = await payments.refund(req.params.id) logger.info({ paymentId: req.params.id, amount: refund.amount }, 'Payment refunded') return refund }, }) ``` Pass `ctx.logger` to the services a request calls: their log lines are tied to the request. `ctx.events` and `ctx.mailer` use the request logger for you. ## Request IDs Each request gets an ID, `crypto.randomUUID()` by default. It is: - `ctx.requestId` in handlers and middlewares; - bound to every line of `ctx.logger`; - sent back in the `X-Request-ID` header of every response, errors included. To reuse the ID set by a gateway or a load balancer, use `generateRequestId`. Accept it only from a proxy you trust, and check its format: ```ts import { createApp, type HttpAdapter } from '@dotpress/core' declare const adapter: HttpAdapter const app = await createApp({ adapter, generateRequestId: (request) => { const id = request.headers['x-request-id'] return typeof id === 'string' && /^[\w-]{8,64}$/.test(id) ? id : crypto.randomUUID() }, }) ``` ## Logging every request A small plugin logs every response with the `onResponse` hook, including the `404` and `405` of the router: ```ts import { definePlugin } from '@dotpress/core' export const httpLogger = definePlugin({ name: 'http-logger', setup(api) { api.hooks.onResponse(({ request, response, requestId, duration }) => { api.logger.info( { requestId, status: response.status, duration: Math.round(duration) }, `${request.method} ${request.path}` ) }) }, }) ``` ```ts const app = await createApp({ adapter, plugins: [httpLogger] }) ``` The hook receives the request, the final response, the request ID, the duration in milliseconds, and the route when one matched (`route.path` is the declared path, such as `/users/:id`: a good label for metrics). ## Reporting errors Unexpected errors are logged with the request logger, then passed to the `onError` hooks: the one of `createApp()`, and those of the plugins (`api.onError()`). See [Errors](https://dotpress.dev/routing/errors.md#unexpected-errors). ```ts const app = await createApp({ adapter, onError: (error, ctx) => errorTracker.capture(error, { requestId: ctx?.requestId }), }) ``` ## Tracing and request-scoped storage The `wrapRequest` hook of a plugin runs the whole pipeline of a request inside a function: a tracing span, or an `AsyncLocalStorage` context that services read without receiving `ctx`. ```ts import { AsyncLocalStorage } from 'node:async_hooks' import { definePlugin } from '@dotpress/core' export const requestStore = new AsyncLocalStorage<{ requestId: string }>() export const requestStorePlugin = definePlugin({ name: 'request-store', setup(api) { api.hooks.wrapRequest((ctx, next) => requestStore.run({ requestId: ctx.requestId }, next)) }, }) ``` The hook must call `next()` once, and return its result. :::tip Coming from v1 Pino is no longer loaded automatically: pass it to `createApp({ logger })`. `enableHttpLogging` and `onRequestComplete` are replaced by the `onResponse` hook of a plugin, and `onException` by `onError`. ::: --- url: https://dotpress.dev/routing/plugins.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Plugins A plugin extends an app with a reusable feature: routes, global middlewares, response filters, context keys and lifecycle hooks. The packages of Dotpress are plugins (`authPlugin()`, `openapiPlugin()`, `mailerPlugin()`…), and your app can have its own. ## Using a plugin Plugins are given to `createApp()`: ```ts const app = await createApp({ adapter, plugins: [authPlugin(auth), openapiPlugin({ info: { title: 'My API', version: '1.0.0' } })], }) ``` They are set up in order, after the plugins they depend on. ## Writing a plugin A plugin is an object declared with `definePlugin()`: a unique `name`, and a `setup()` function that receives the plugin API. A function that takes options and returns the plugin keeps it configurable: ```ts import { declareContextKey, definePlugin } from '@dotpress/core' export interface FeatureFlags { isEnabled(flag: string): boolean all(): Record } export interface FlagSource { forTenant(tenantId: string | undefined): Promise close(): Promise } // The new context key, typed in every handler of the program. declare module '@dotpress/core' { interface RequestContext { flags: Promise } } // Using ctx.flags without the plugin throws an explicit error, which names // the function to install: featureFlagsPlugin. declareContextKey('flags', 'featureFlagsPlugin') export const featureFlagsPlugin = (source: FlagSource) => definePlugin({ name: 'featureFlags', setup(api) { // Computed on first access, once per request. api.decorateContext('flags', (ctx) => source.forTenant(ctx.req.header('x-tenant-id'))) api.defineRoute({ path: '/flags', handler: async ({ flags }) => (await flags).all(), }) api.hooks.onClose(() => source.close()) }, }) ``` Handlers of the app then use `ctx.flags`, typed: ```ts handler: async ({ flags }) => ((await flags).isEnabled('new-checkout') ? newCheckout() : checkout()) ``` ## The plugin API | Method | Description | | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `defineRoute(route)` | Adds a route, like `defineRoute()` | | `createGroup(prefix, middlewares)` | Adds a group of routes | | `addGlobalMiddleware(middleware)` | Runs on every route, before the middlewares of `createApp()` | | `addResponseFilter(filter)` | Filters every JSON response, after the filters of `createApp()` | | `decorateContext(key, factory)` | Provides a context key declared by module augmentation, computed on first access | | `onError(hook)` | Receives the unexpected errors, like the `onError` option of `createApp()` | | `hooks.onInit`, `onReady`, `onRequest`, `wrapRequest`, `onResponse`, `onClose` | Lifecycle hooks, see below | | `getRoutes()` | The routes of the app, from `onInit` | | `getPlugin(name)`, `getPlugins()` | The other plugins | | `logger` | A logger bound to the plugin | | `basePath`, `publicBasePath`, `publicPath(path)` | The paths of the app, see [Base path](https://dotpress.dev/routing/http-options.md#base-path) | | `cors` | The CORS settings of the app (`credentials`, `isOriginAllowed(req)`) | Registration methods are only available during `setup()`, which can be `async`: they throw once it has returned. ## Hooks | Hook | When | | ------------------------ | -------------------------------------------------------------------------------------------------------------- | | `onInit` | After every plugin is set up and the routes are compiled: inspect the routes | | `onReady` | After the routes are mounted on the server, before `listen()` | | `onRequest(ctx)` | For each request matching a route, before the middlewares. Can stop the request, like a middleware. | | `wrapRequest(ctx, next)` | Runs the pipeline of each request inside a function: tracing, request-scoped storage | | `onResponse(event)` | For every response, `404` included: logging, metrics. Can replace the response. | | `onClose` | When `app.close()` is called, after the server has stopped, in reverse order of the plugins: close connections | See [Logging and error hooks](https://dotpress.dev/routing/logging.md) for examples. ## Dependencies between plugins A plugin that needs another one declares it with `dependsOn`: it is set up after it, whatever the order of `plugins`. A missing or circular dependency makes `createApp()` throw. ```ts definePlugin({ name: 'auditLog', dependsOn: ['auth'], // the name of authPlugin() setup(api) { // … }, }) ``` The other properties of a plugin object are visible to other plugins through `api.getPlugin(name)`: a plugin can expose a service to the plugins that depend on it. ## Plugin or middleware? | Need | Use | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | A check on some routes | a middleware on the routes or a group | | A check on every route | a global middleware of `createApp()` | | A feature reused across apps, with routes, context keys or hooks | a plugin | | Services of your app in `ctx` | a small plugin, see [Project structure](https://dotpress.dev/getting-started/project-structure.md#handlers-find-their-services-in-ctx) | :::tip Coming from v1 Plugins are objects declared with `definePlugin()`, no longer functions. `addGroup()` is renamed `createGroup()`, and `useBeforeRoutes()` / `useAfterRoutes()` are removed: plugins do not depend on a server, native middlewares go to the adapter options. Plugins gain dependencies, lifecycle hooks and context keys. ::: --- url: https://dotpress.dev/routing/testing.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Testing A Dotpress app is tested in memory: the memory adapter of `@dotpress/testing` runs the requests through the real pipeline, with the routes, middlewares, validation and plugins of the app, without opening a port. The tests are fast, and need no mock of the framework. ```sh npm install -D @dotpress/testing vitest ``` `@dotpress/testing` needs [Vitest](https://vitest.dev): its assertions (`expectMailSent()`, `expectEventEmitted()`…) and the conformance suite of the adapters are built on it. ## Test routes `createTestApp()` creates an app on the memory adapter, with the routers and plugins you give it, and returns a `fetch()` relative to `http://localhost`: ```ts title="test/articles.test.ts" import { createTestApp } from '@dotpress/testing' import { afterEach, expect, it } from 'vitest' import { articlesRouter } from '../src/articles.ts' let close: () => Promise afterEach(() => close()) it('rejects an article without title', async () => { const app = await createTestApp({ routers: [articlesRouter] }) close = app.close const res = await app.fetch('/articles', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: '' }), }) expect(res.status).toBe(400) expect(await res.json()).toMatchObject({ error: 'VALIDATION_FAILED' }) }) ``` `app.logger` records the log lines instead of printing them: tests stay quiet, and can check what was logged. ## Test the app as in production When the app is created by a function of yours (see [Project structure](https://dotpress.dev/getting-started/project-structure.md)), give it the memory adapter and in-memory services. The test runs the app exactly as configured in production: ```ts title="test/tasks.test.ts" import { createMemoryLogger, memoryAdapter } from '@dotpress/testing' import { beforeEach, expect, it } from 'vitest' import { createTasksApp } from '../src/app.ts' import { createMemoryStore } from './support.ts' let adapter: ReturnType beforeEach(async () => { adapter = memoryAdapter() await createTasksApp({ adapter, store: createMemoryStore(), logger: createMemoryLogger() }) }) it('creates a task and reads it back', async () => { const created = await adapter.fetch( new Request('http://localhost/tasks', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'Write the tests' }), }) ) expect(created.status).toBe(201) const task = await created.json() const res = await adapter.fetch(new Request(`http://localhost/tasks/${task.id}`)) expect(await res.json()).toEqual(task) }) ``` Each test creates its own app and services: no state leaks from one test to the next. ## Authenticated requests With `@dotpress/auth`, log in through the real route, or generate a token with the auth service, and send it like a client: ```ts const { accessToken } = await auth.generateTokensForUser({ userId: user.id }) const res = await app.fetch('/profile', { headers: { authorization: `Bearer ${accessToken}` }, }) ``` ## On a real server A few tests can run the app on its real server, to check the integration with it (native middlewares, proxy settings). Listen on port `0` to get a free port: ```ts import { expressAdapter } from '@dotpress/adapter-express' const adapter = expressAdapter() const app = await createTasksApp({ adapter }) const { port } = await app.listen(0, '127.0.0.1') const res = await fetch(`http://127.0.0.1:${port}/tasks`) await app.close() ``` The memory adapter passes the same conformance suite as the other adapters: the behavior tested in memory is the behavior on the server. ## Events, emails and Lambda `@dotpress/testing` also checks the events emitted and the emails sent, and runs a Lambda handler with simulated events. See [Testing helpers](https://dotpress.dev/services/testing.md). --- url: https://dotpress.dev/adapters/index.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Choosing an adapter An adapter connects your app to an HTTP server. Your routes, middlewares, errors and tests do not depend on it: switching from one adapter to another changes one line of `createApp()`. ```ts // Express const app = await createApp({ adapter: expressAdapter(), routers }) // Fastify const app = await createApp({ adapter: fastifyAdapter(), routers }) // Hono, on Node.js const app = await createApp({ adapter: honoAdapter(), routers }) ``` ## Compared | | Express | Fastify | Hono | | --------------------------------- | --------------------------- | --------------------------- | --------------------------- | | Package | `@dotpress/adapter-express` | `@dotpress/adapter-fastify` | `@dotpress/adapter-hono` | | Versions | Express 4 and 5 | Fastify 5 | Hono 4.13 or later | | Node.js server | ✓ | ✓ | ✓, with `@hono/node-server` | | AWS Lambda | — | ✓ | ✓ | | Native extensions | Express middlewares | Fastify plugins and hooks | Hono middlewares | | Lambda bundle (example, minified) | — | about 1.1 MB | about 510 kB | ## Which one? - **Your team knows one of them, or your app already runs on it**: take that one. Mount Dotpress on your existing application, next to its native routes, and move them over time. - **You need middlewares or plugins of a specific ecosystem** (`helmet`, `@fastify/rate-limit`, Hono middlewares…): take the server of that ecosystem. - **The API runs on AWS Lambda**: take Hono for the smallest bundle, or Fastify if you need its plugins. - **No preference**: any of them works the same with Dotpress. You can change your mind later. Coming from Dotpress 1, which ran on Express: keep [Express](https://dotpress.dev/adapters/express.md) to migrate in small steps. ## The same behavior everywhere Whatever the adapter, Dotpress itself: - **matches the routes**, with the same rules: case-sensitive, static segments before parameters, trailing slashes ignored, `405` with an `Allow` header; - **reads and parses the bodies**: JSON, forms, text, multipart uploads, with the same size limit and errors; - **builds the responses**, including streams and Server-Sent Events; - **formats the errors**, including the client errors of native middlewares (a `4xx` keeps its status). Every adapter passes the same conformance test suite of `@dotpress/testing`, which covers routing, parsing, validation, errors, middlewares and responses. ## Common options | Option | Description | | ------------------- | ---------------------------------------------------------------------------- | | `app` | An existing Express, Fastify or Hono application. A new one by default. | | `beforeRoutes(app)` | Registers native middlewares, plugins and routes before the Dotpress routes. | | `afterRoutes(app)` | Registers native middlewares and routes after the Dotpress routes. | | `bodyLimit` | Maximum request body size, in bytes. 1 MiB by default. | The app also gives access to the server: - `app.native()` returns the native application (Express app, Fastify instance, Hono app); - `adapter.server()` returns the Node.js HTTP server started by `listen()`; - `ctx.raw` is the native request (or context), as an escape hatch in a route. `app.close()` waits for the pending requests, closes the responses being streamed, then runs the `onClose` hooks of the plugins: call it on `SIGTERM` for a graceful shutdown (see [Node.js and containers](https://dotpress.dev/deployment/node.md)). ## In tests The memory adapter of `@dotpress/testing` is an adapter too: it runs the requests in memory, without a port. See [Testing](https://dotpress.dev/routing/testing.md). Every option and member of the adapters, and of their Lambda handlers: see the [Adapters reference](https://dotpress.dev/reference/adapters.md). --- url: https://dotpress.dev/adapters/express.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Express `@dotpress/adapter-express` runs your app on [Express](https://expressjs.com) 4 or 5. ```sh [npm] npm install @dotpress/core @dotpress/adapter-express express zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-express express zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-express npm:express npm:zod ``` ```sh [npm] npm install -D @types/express ``` ```sh [yarn] yarn add -D @types/express ``` ```sh [pnpm] pnpm add -D @types/express ``` ```sh [bun] bun add -D @types/express ``` ```sh [deno] deno add -D npm:@types/express ``` ```ts import { createApp, defineRoute } from '@dotpress/core' import { expressAdapter } from '@dotpress/adapter-express' defineRoute({ path: '/hello', handler: () => ({ message: 'Hello' }) }) const app = await createApp({ adapter: expressAdapter() }) await app.listen(3000) ``` ## Options | Option | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `app` | An existing Express application (Express 4 or 5). By default, a new `express()` application, with `X-Powered-By` and `ETag` disabled. | | `beforeRoutes(app)` | Registers native middlewares before the Dotpress routes. | | `afterRoutes(app)` | Registers native middlewares and routes after the Dotpress routes, before the not-found handler. | | `bodyLimit` | Maximum request body size, in bytes. 1 MiB by default. | ## Express middlewares Middlewares of the Express ecosystem go in `beforeRoutes`: ```ts import compression from 'compression' import helmet from 'helmet' const app = await createApp({ adapter: expressAdapter({ beforeRoutes: (app) => { app.use(helmet()) app.use(compression()) }, }), }) ``` They run before Dotpress, for every request. Keep the logic of your API in [Dotpress middlewares](https://dotpress.dev/routing/middlewares.md): they see the matched route and the typed context, run on every adapter, and are tested in memory. ## An existing application Pass your application with `app`: its settings, middlewares and routes stay, and the Dotpress routes are added to it. A project can move its routes to Dotpress one at a time. ```ts import express from 'express' const legacy = express() legacy.set('trust proxy', 1) // behind one proxy: ctx.req.ip is the client address legacy.get('/legacy/status', (req, res) => res.json({ ok: true })) const app = await createApp({ adapter: expressAdapter({ app: legacy }) }) ``` ## Behavior - **Routes are matched by Dotpress**, with the same rules on every adapter. Express settings such as `case sensitive routing` or `strict routing` do not apply to them. - **Bodies are read by the adapter**: JSON, forms and text are parsed, and uploads without Multer. A body already parsed by a native middleware (`express.json()`, `multer`…) is used as is. Routes declared with `rawBody: true` need the exact bytes: do not register a native body parser for them. - **Errors passed to `next(error)`** by native middlewares use the Dotpress error format: a `4xx` `status` is kept, anything else is a `500` reported to `onError`. - **`ctx.req.ip`** honors the `trust proxy` setting of Express. - **`ctx.raw`** is the Express request. - **`close()`** waits for pending requests and closes the responses being streamed. - **`adapter.server()`** returns the Node.js HTTP server started by `listen()`. ## Your own HTTP server To serve HTTPS from Node.js, or share a server, mount the Express application yourself: ```ts import https from 'node:https' const app = await createApp({ adapter: expressAdapter() }) https.createServer(tlsOptions, app.native()).listen(443) ``` ## AWS Lambda The Express adapter has no Lambda entry. Your routes do not depend on the adapter: use the [Hono or Fastify adapter on AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md), and keep Express for your servers if you like. ## Example The [Express example](https://dotpress.dev/examples/express.md) is a tasks API with route groups, validation, returned errors, OpenAPI, and tests in memory and over HTTP. :::tip Coming from v1 `useBeforeRoutes` and `useAfterRoutes` of `createApp()` become the `beforeRoutes` and `afterRoutes` options of the adapter. `createApp()` no longer returns the Express application: use `app.native()`. ::: --- url: https://dotpress.dev/adapters/fastify.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Fastify `@dotpress/adapter-fastify` runs your app on [Fastify](https://fastify.dev) 5, on Node.js and [AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md). ```sh [npm] npm install @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-fastify fastify zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-fastify npm:fastify npm:zod ``` ```ts import { createApp, defineRoute } from '@dotpress/core' import { fastifyAdapter } from '@dotpress/adapter-fastify' defineRoute({ path: '/hello', handler: () => ({ message: 'Hello' }) }) const app = await createApp({ adapter: fastifyAdapter() }) await app.listen(3000) ``` ## Options | Option | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `app` | An existing Fastify instance. `Fastify()` by default. | | `beforeRoutes(app)` | Registers hooks, plugins and native routes. Hooks registered here apply to the Dotpress routes. | | `afterRoutes(app)` | Registers hooks, plugins and native routes in an encapsulated context: they do not apply to the Dotpress routes, except plugins wrapped with `fastify-plugin`. | | `bodyLimit` | Maximum request body size, in bytes. 1 MiB by default. | ## Fastify plugins and hooks Register Fastify plugins and hooks in `beforeRoutes`, which can be `async`: they apply to the Dotpress routes too. ```ts import helmet from '@fastify/helmet' const app = await createApp({ adapter: fastifyAdapter({ beforeRoutes: async (app) => { await app.register(helmet) }, }), }) ``` The instance is ready once `createApp()` resolves: register everything in `beforeRoutes` or `afterRoutes`. ## An existing instance The app of the [Fastify example](https://dotpress.dev/examples/fastify.md) mounts the Dotpress routes on an existing instance, next to a native route, with a Fastify hook applied to both: ```ts file="/../examples/fastify/src/app.ts" import { fastifyAdapter } from '@dotpress/adapter-fastify' import { createApp, type Logger } from '@dotpress/core' import Fastify from 'fastify' import { createNoteStore } from './notes.ts' import { notesRouter } from './routes.ts' /** * Mounts the Dotpress routes on a Fastify instance, next to its native * routes. Used by the server (`server.ts`) and the Lambda handler * (`lambda.ts`). */ export const createNotesApp = (options: { logger?: Logger } = {}) => { // An existing instance: its plugins, hooks and native routes stay. const fastify = Fastify() fastify.get('/health', async () => ({ status: 'ok' })) return createApp({ adapter: fastifyAdapter({ app: fastify, // Hooks and plugins registered here apply to the Dotpress routes too. beforeRoutes: (app) => { app.addHook('onRequest', async (request, reply) => { reply.header('x-request-id', request.id) }) }, }), ...(options.logger && { logger: options.logger }), routers: [notesRouter(createNoteStore())], }) } ``` ## Behavior - **Each Dotpress route is a native Fastify route.** Its path (`request.routeOptions.url`, `/users/:id`) shows in the Fastify logs, metrics and traces, and a native route with the same method and path fails at startup. Routing still follows the Dotpress rules: trailing slashes ignored, `HEAD` on `GET` routes, `405` with `Allow`. - **Bodies are read by Dotpress**, with the same rules on every adapter: the Fastify body parsers only apply to native routes, and `@fastify/multipart` is not needed for uploads. `preParsing` hooks apply. Like Fastify, the adapter does not read the bodies of `GET` and `HEAD` requests. - **Errors** with a `4xx` `statusCode` raised by Fastify or its plugins (`@fastify/rate-limit`, `@fastify/sensible`…) use the Dotpress error format and keep their status and message. Other errors are unexpected (`500`). The adapter takes over the not-found and error handlers of the instance: they apply to native routes too. - **`ctx.req.ip`** is `request.ip`: proxy headers are only used with the `trustProxy` option of Fastify, set when you create the instance. - **Streamed responses** (`stream()`, `sse()`) are written directly to the Node.js response, so that their headers are sent at once: `onSend` hooks, such as `@fastify/compress`, do not apply to them. - **`ctx.raw`** is the Fastify request. - **`listen(port, host?)`** listens on every interface without `host`, like Node.js. **`close()`** closes the instance (its `onClose` hooks), waits for pending requests and closes the streamed responses. ## Testing with inject() Besides the [memory adapter](https://dotpress.dev/routing/testing.md), Fastify tests can use `inject()`, which goes through the Fastify hooks and plugins without opening a port: ```ts const adapter = fastifyAdapter() await createApp({ adapter, routers }) const res = await adapter.native().inject('/hello') ``` ## On AWS Lambda The same app runs on AWS Lambda with `createLambdaHandler()` of `@dotpress/adapter-fastify/lambda`: see [AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md). --- url: https://dotpress.dev/adapters/hono.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Hono `@dotpress/adapter-hono` runs your app on [Hono](https://hono.dev) 4.13 or later, on Node.js and [AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md). Hono 5 is tested against its release candidate. ## On Node.js ```sh [npm] npm install @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-hono hono @hono/node-server zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-hono npm:hono npm:@hono/node-server npm:zod ``` ```ts import { createApp, defineRoute } from '@dotpress/core' import { honoAdapter } from '@dotpress/adapter-hono/node' defineRoute({ path: '/hello', handler: () => ({ message: 'Hello' }) }) const app = await createApp({ adapter: honoAdapter() }) await app.listen(3000) ``` The `@dotpress/adapter-hono/node` entry serves the app with [`@hono/node-server`](https://github.com/honojs/node-server). The main entry, `@dotpress/adapter-hono`, has no Node.js server: it is the one to use on AWS Lambda, where the bundle stays small. ## Options | Option | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------ | | `app` | An existing Hono application. `new Hono()` by default. | | `beforeRoutes(app)` | Registers native middlewares and routes before the Dotpress routes. | | `afterRoutes(app)` | Registers native middlewares and routes after the Dotpress routes, before the not-found handler. | | `bodyLimit` | Maximum request body size, in bytes. 1 MiB by default. | | `getIp(c)` | The client IP address (`ctx.req.ip`). By default, the address given by the runtime: the socket address on Node.js. | ## Hono middlewares The [Hono example](https://dotpress.dev/examples/hono.md) shares its adapter options between Node.js and AWS Lambda, with a native middleware and a native route: ```ts file="/../examples/hono/src/app.ts" import type { HonoAdapterOptions } from '@dotpress/adapter-hono' import { createApp, type HttpAdapter, type Logger } from '@dotpress/core' import type { Hono } from 'hono' import { secureHeaders } from 'hono/secure-headers' import { createNoteStore } from './notes.ts' import { notesRouter } from './routes.ts' /** Options of the Hono adapter, the same on Node.js and AWS Lambda. */ export const honoOptions: HonoAdapterOptions = { // Native Hono middlewares and routes, before the Dotpress routes. beforeRoutes: (app) => { app.use('*', secureHeaders()) app.get('/health', (c) => c.json({ status: 'ok' })) }, } /** * Creates the app on a Hono adapter: `honoAdapter()` of * `@dotpress/adapter-hono/node` in `node.ts`, of `@dotpress/adapter-hono` * in `lambda.ts` and the tests. */ export const createNotesApp = ( adapter: TAdapter, options: { logger?: Logger } = {} ) => createApp({ adapter, ...(options.logger && { logger: options.logger }), routers: [notesRouter(createNoteStore())], }) ``` ```ts file="/../examples/hono/src/node.ts" // The Node.js entry: @hono/node-server serves the app. import { honoAdapter } from '@dotpress/adapter-hono/node' import { createNotesApp, honoOptions } from './app.ts' const port = Number(process.env.PORT ?? 3000) const app = await createNotesApp(honoAdapter(honoOptions)) await app.listen(port) console.log(`Notes API: http://localhost:${port}/notes`) // Waits for pending requests, then runs the onClose hooks of the plugins. for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, () => void app.close()) } ``` ## Behavior - **Routes are matched by Dotpress**, with the same rules on every adapter: Hono options such as `strict` do not apply. Use the `basePath` option of `createApp()` rather than `app.basePath()`. - **Bodies are read by the adapter**: JSON, forms, text and multipart uploads. A body already read by a native middleware through Hono (`c.req.json()`, `c.req.parseBody()`…) is taken from its cache. Routes declared with `rawBody: true` need the exact bytes: let the adapter read the body, or read it with `c.req.arrayBuffer()` or `c.req.blob()` in a native middleware. - **`HTTPException` client errors** (`4xx`) thrown by native middlewares use the Dotpress error format and keep their status, message and headers (the `WWW-Authenticate` header of `bearerAuth()`…). Other errors are unexpected (`500`). The adapter takes over `app.notFound()` and `app.onError()`. - **`ctx.req.ip`** does not read proxy headers such as `X-Forwarded-For`: behind a proxy, read them in `getIp(c)`, and only trust the proxies you run. - **`ctx.raw`** is the Hono context. - **`close()`** waits for pending requests and closes the responses being streamed; `adapter.server()` returns the Node.js HTTP server. ## Other runtimes The main entry only relies on Hono and Web-standard APIs. `adapter.fetch` handles a Web `Request`, like `app.fetch` in Hono, for runtimes that take a `fetch` handler: ```ts import { honoAdapter } from '@dotpress/adapter-hono' const adapter = honoAdapter() await createApp({ adapter, routers }) export default { fetch: adapter.fetch } ``` :::warning Dotpress 2.0 is tested on Node.js and AWS Lambda only: other runtimes (Bun, Deno, edge runtimes) are not officially supported yet. See [the design decision](https://dotpress.dev/reference/design-decisions/edge.md). ::: ## On AWS Lambda The same app runs on AWS Lambda with `createLambdaHandler()` of `@dotpress/adapter-hono/lambda`: see [AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md). --- url: https://dotpress.dev/adapters/aws-lambda.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # AWS Lambda The Hono and Fastify adapters run your app on [AWS Lambda](https://aws.amazon.com/lambda/), behind: - an API Gateway REST API (payload v1); - an API Gateway HTTP API or a Function URL (payload v2); - an Application Load Balancer. The routes are the same as on a server: only the entry point changes. ## The handler Both adapters provide `createLambdaHandler()`. It takes a function that creates the app. ### With Hono ```sh [npm] npm install @dotpress/core @dotpress/adapter-hono hono @hono/aws-lambda zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-hono hono @hono/aws-lambda zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-hono hono @hono/aws-lambda zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-hono hono @hono/aws-lambda zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-hono npm:hono npm:@hono/aws-lambda npm:zod ``` ```ts file="/../examples/hono/src/lambda.ts" // The AWS Lambda entry: API Gateway (REST and HTTP APIs), Function URLs and // Application Load Balancers. The main entry of the adapter has no Node.js // server: the bundle stays small. import { honoAdapter } from '@dotpress/adapter-hono' import { createLambdaHandler } from '@dotpress/adapter-hono/lambda' import { createNotesApp, honoOptions } from './app.ts' // The app is created at the first invocation (cold start), then reused by // the next invocations of the execution environment. export const handler = createLambdaHandler(() => createNotesApp(honoAdapter(honoOptions)) ) ``` Use the main entry of the adapter, `@dotpress/adapter-hono`, not `/node`: it has no Node.js server, and keeps the bundle small. ### With Fastify ```sh [npm] npm install @dotpress/core @dotpress/adapter-fastify fastify @fastify/aws-lambda zod ``` ```sh [yarn] yarn add @dotpress/core @dotpress/adapter-fastify fastify @fastify/aws-lambda zod ``` ```sh [pnpm] pnpm add @dotpress/core @dotpress/adapter-fastify fastify @fastify/aws-lambda zod ``` ```sh [bun] bun add @dotpress/core @dotpress/adapter-fastify fastify @fastify/aws-lambda zod ``` ```sh [deno] deno add npm:@dotpress/core npm:@dotpress/adapter-fastify npm:fastify npm:@fastify/aws-lambda npm:zod ``` ```ts file="/../examples/fastify/src/lambda.ts" import { createLambdaHandler } from '@dotpress/adapter-fastify/lambda' import { createNotesApp } from './app.ts' // API Gateway (REST and HTTP APIs), Function URLs and Application Load // Balancers. The app is created at the first invocation (cold start), then // reused by the next invocations of the execution environment. export const handler = createLambdaHandler(() => createNotesApp()) ``` The handler of Fastify sends the events to `inject()` of the instance, through [`@fastify/aws-lambda`](https://github.com/fastify/aws-lambda-fastify): the Fastify hooks and plugins apply. ## How the handler behaves - **Lazy creation.** The app is created at the first invocation (the cold start), and reused by the next invocations of the execution environment. Invocations received meanwhile wait for the same app. The `handler` export stays synchronous: no top-level `await` in the module. - **Recoverable failures.** When the app cannot be created (a missing secret, a database down), the error is logged, the invocation gets the standard `500` error, and the next invocation tries again. - **Buffered responses.** Responses are sent once complete. `stream()` works for finite streams; Server-Sent Events (`sse()`) are not supported. A stream that fails is never sent truncated: with Fastify, the invocation gets an empty `500`; with Hono, the invocation fails, and AWS answers `502` (`500` behind an HTTP API). Lambda response streaming is not supported yet. - **Binary responses** are sent in base64: every content type except text, JSON and XML (and, with Fastify, compressed responses), or as decided by the `isContentTypeBinary(contentType)` option. Behind a REST API, set its binary media types to `*/*`: see [REST APIs](https://dotpress.dev/deployment/aws-lambda.md#rest-apis). - **Query strings**, with Fastify, are read as sent when the event has them (payload v2, load balancers): plus signs and commas keep their meaning, as on the other adapters. - **`ctx.req.ip`** is the source IP of API Gateway, or the last `X-Forwarded-For` entry behind a load balancer (`127.0.0.1` with Fastify when the event has no address). Behind CloudFront or another proxy, read the right header with the `getIp(c)` option of `honoAdapter()`, or the `trustProxy` option of Fastify. - **Load balancers**: enable the multi-value headers of the target group (`lambda.multi_value_headers.enabled`, off by default), to receive repeated query keys and send several cookies. Without them, each query key keeps its last value, and a response sends its first cookie only: the cookie mode of `@dotpress/auth`, which needs two cookies, does not work. The load balancer also makes a relative `Location` header absolute, with the host of the request. - **The Lambda event and context**, with Hono, are in the Hono context: `ctx.raw.env.event` and `ctx.raw.env.lambdaContext`. With Fastify, they are not given to the routes. | Option of `createLambdaHandler()` | Description | | ---------------------------------- | ----------------------------------------------------------------- | | `logger` | Logs the failures to create the app. A console logger by default. | | `isContentTypeBinary(contentType)` | Whether a response is sent in base64. | ## Configuration and secrets Create the services of the app inside the factory, not at the top of the module: a failure is then retried at the next invocation, instead of breaking the execution environment for good. ```ts export const handler = createLambdaHandler(async () => { const config = loadConfig() const db = await connectDatabase(config.DATABASE_URL) return createApp({ adapter: honoAdapter(), routers, plugins: [servicesPlugin({ db })] }) }) ``` Database connections created in the factory are reused by the next invocations of the execution environment. Size the connection pools for many small environments, or use a proxy such as RDS Proxy. ## Bundle the handler Bundle the handler and its dependencies into one file, for instance with [esbuild](https://esbuild.github.io): ```sh # Hono esbuild src/lambda.ts --bundle --minify --platform=node --target=node22 \ --format=esm --outfile=dist/lambda.mjs ``` Fastify and its dependencies are CommonJS modules: an ES module bundle must define `require` for them. ```sh # Fastify esbuild src/lambda.ts --bundle --minify --platform=node --target=node22 \ --format=esm --outfile=dist/lambda.mjs \ --banner:js="import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" ``` In the examples, the Hono bundle weighs about 510 kB minified (115 kB gzipped), and the Fastify bundle about 1.1 MB (300 kB gzipped). Deploy `dist/lambda.mjs` with your tool (AWS SAM, CDK, Serverless Framework, Terraform…): runtime Node.js 22 or later, handler `lambda.handler`. See [Deployment on AWS Lambda](https://dotpress.dev/deployment/aws-lambda.md). ## CORS Configure CORS either in API Gateway or Function URLs, or in Dotpress, not both: AWS answers the preflight requests before the function runs. See [CORS](https://dotpress.dev/routing/http-options.md#cors). ## Testing `createLambdaTarget()` of `@dotpress/testing` sends simulated API Gateway and load balancer events to your handler, without an AWS account: see [Testing helpers](https://dotpress.dev/services/testing.md). The [Hono](https://dotpress.dev/examples/hono.md) and [Fastify](https://dotpress.dev/examples/fastify.md) examples test their handler and their bundle this way. ## Event workers on Lambda Listeners of [`@dotpress/events`](https://dotpress.dev/services/events.md) can run on Lambda too, triggered by SQS: see [Event workers](https://dotpress.dev/deployment/event-workers.md). --- url: https://dotpress.dev/auth/index.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Authentication `@dotpress/auth` authenticates the users of your API with a username and a password, and keeps them logged in with short-lived access tokens and rotating refresh tokens. It works with any database, through a small data provider, and on every adapter. What it gives you: - **the routes**: login, token refresh, current user, cookie session restore, logout; - **`ctx.user` and `ctx.auth`**, typed, in every handler, and guards: `requireAuth`, `requireRole()`, `requireClient()`; - **sessions for browsers** in `httpOnly` cookies, protected against cross-site request forgery; - **security by default**: refresh token rotation with reuse detection, login throttling, constant-time login failures, bcrypt hashing, RFC 9068 access tokens checked on every request. ## How it works 1. The client logs in with a username and a password. It gets an **access token**, valid 15 minutes, and a **refresh token**. 2. It sends the access token with each request. The plugin verifies it, loads the user, and sets `ctx.user`. 3. Before the access token expires, the client exchanges the refresh token for a new pair. The old refresh token can no longer be used: a stolen one is detected when it comes back. 4. A logout revokes the session. The access token is a JWT signed with your RSA key: verifying it costs no database lookup of the token. The refresh token is a random value; only its SHA-256 hash is stored, in your database. ## Install ```sh [npm] npm install @dotpress/auth@beta ``` ```sh [yarn] yarn add @dotpress/auth@beta ``` ```sh [pnpm] pnpm add @dotpress/auth@beta ``` ```sh [bun] bun add @dotpress/auth@beta ``` ```sh [deno] deno add npm:@dotpress/auth@beta ``` :::warning During the beta Install `@dotpress/auth` with the `beta` tag: without it, npm installs `@dotpress/auth` 1.x, the plugin of Dotpress 1. ::: ## Set up Describe your user, create the auth service, and install its plugin: ```ts import { createApp, defineRoute, type HttpAdapter } from '@dotpress/core' import { authPlugin, createAuth, requireAuth, type DataProvider } from '@dotpress/auth' declare const adapter: HttpAdapter declare const dataProvider: DataProvider declare const env: { JWT_PRIVATE_KEY: string; JWT_PUBLIC_KEY: string } // The type of ctx.user: what dataProvider.findUserById() returns. declare module '@dotpress/auth' { interface AuthUser { id: string email: string roles: string[] } } const auth = createAuth({ keys: { privateKey: env.JWT_PRIVATE_KEY, // PKCS#8 PEM, "BEGIN PRIVATE KEY" publicKey: env.JWT_PUBLIC_KEY, // SPKI PEM, "BEGIN PUBLIC KEY" }, issuer: 'https://api.example.com', // required, one per environment dataProvider, // your users and refresh tokens, see Data provider }) defineRoute({ path: '/profile', middlewares: [requireAuth], handler: ({ user }) => ({ email: user.email }), }) const app = await createApp({ adapter, plugins: [authPlugin(auth)] }) ``` See [Data provider](https://dotpress.dev/auth/data-provider.md) to connect your database, and [Keys and rotation](https://dotpress.dev/auth/keys.md) to generate the keys. ## The routes | Route | Description | | -------------------- | ------------------------------------------------------------------------------------------------- | | `POST /auth/login` | `{ username, password, clientId?, mode? }`: logs in. `mode: 'cookie'` sets the tokens as cookies. | | `POST /auth/refresh` | Exchanges a refresh token for a new pair. | | `GET /auth/me` | The authenticated user. | | `POST /auth/restore` | Restores a cookie session: the user and the expiration of the session. | | `POST /auth/logout` | `{ refreshToken?, scope? }`: revokes the current session, or every session with `scope: 'all'`. | Each route answers with `userId`, `expiresIn` and `expiresAt` (the expiration of the access token), so that the client knows when to refresh. The tokens are in the body, or in cookies (see below). `authPlugin(auth, { prefix: '/api/auth' })` changes the prefix; `{ routes: false }` keeps only the authentication of the requests, for an API that only verifies tokens. ## Browsers or other clients The same API serves two kinds of clients: | Client | Tokens | Configuration | | --------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Browser application | Both tokens in `httpOnly` cookies: the JavaScript of the page never sees them | `cookies: { enabled: true, accessTokenInCookie: true }`, login with `mode: 'cookie'` | | Mobile application, another service, a script | Both tokens in the body; the access token in the `Authorization: Bearer` header | the default | :::tip Recommended for browsers Use the cookie mode with `accessTokenInCookie`. A token stored in `localStorage`, or in any variable of the page, can be stolen by a single injected script (XSS); an `httpOnly` cookie cannot. See [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md). ::: ## Without an app The auth service works in scripts and workers too: ```ts const hash = await auth.hashPassword(password) const { accessToken, refreshToken } = await auth.generateTokensForUser({ userId }) const session = await auth.verifyAccessToken(accessToken) ``` ## In this section - [Data provider](https://dotpress.dev/auth/data-provider.md): connect your database. - [Protecting routes](https://dotpress.dev/auth/protecting-routes.md): guards, roles, the type of the user. - [Sessions and tokens](https://dotpress.dev/auth/sessions.md): lifetimes, rotation, logout, revocation. - [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md): sessions for browsers. - [Clients](https://dotpress.dev/auth/clients.md): several applications on one API. - [Passwords and brute force](https://dotpress.dev/auth/passwords.md). - [Keys and rotation](https://dotpress.dev/auth/keys.md). - [Security checklist](https://dotpress.dev/auth/security.md): what to check before going to production. - [Auth reference](https://dotpress.dev/reference/auth.md): every setting, route, error and contract. The [Auth example](https://dotpress.dev/examples/auth.md) puts it all together: sign-up, both modes, rotation, logout of one or every device, password change, roles. :::tip Coming from v1 `configurePlugin()` is replaced by `createAuth()` and `authPlugin(auth)`. Access tokens follow RFC 9068, `issuer` is required, logout revokes the current session only, login attempts are throttled, and tokens set as cookies are no longer returned in the body. See [Migrate from v1](https://dotpress.dev/reference/migrate-from-v1.md). ::: --- url: https://dotpress.dev/auth/data-provider.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Data provider `@dotpress/auth` stores nothing itself. A data provider, an object of a few functions, reads your users and stores the refresh tokens in your database, with the library of your choice. ## The methods | Method | Required | Called | | ------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `findUserIdentifiers(username)` | ✓ | At login: `{ userId, passwordHash, role? }`, or `undefined` for an unknown username. `passwordHash` is `null` for an account without password (SSO). | | `findUserById(userId)` | ✓ | On every authenticated request and every refresh: the user, which becomes `ctx.user` | | `storeRefreshToken(payload)` | ✓ | At login and at each refresh: `{ tokenHash, userId, accessTokenId, sessionId, expiresAt }`. The token itself is never given: only its SHA-256 hash. | | `findRefreshToken(tokenHash)` | ✓ | At each refresh and logout: `{ userId, accessTokenId, sessionId, expiresAt, isUsed, usedAt, revokedAt }`, or `undefined`. `isUsed` can be derived from `usedAt`. | | `markRefreshTokenAsUsed(tokenHash, usedAt)` | ✓ | At each refresh | | `revokeSessionTokens(sessionId)` | ✓ | At logout, and when a stolen refresh token is detected: revokes one session | | `revokeUserTokens(userId)` | ✓ | At logout of every device, and by `auth.revokeUserSessions(userId)`: revokes every session of the user | | `isSessionRevoked(sessionId)` | | On every authenticated request: rejects the access tokens of a revoked session at once, see [Revocation](https://dotpress.dev/auth/sessions.md#revocation) | | `updatePasswordHash(userId, passwordHash)` | | After a successful login, when the cost of the hash changed, see [Passwords](https://dotpress.dev/auth/passwords.md#raising-the-cost) | :::warning findUserById decides who is logged in `findUserById()` must return `undefined` for a deleted, disabled or banned account. It is called on every request: the user is logged out at once, and their sessions are revoked at the next refresh. ::: Return only what the handlers need from `findUserById()`: it becomes `ctx.user`, and is returned by `GET /auth/me`. Never the password hash. ## The refresh tokens table A refresh token is stored by its SHA-256 hash, never in clear. The tokens of a session share a `sessionId`, the session ID: ```sql CREATE TABLE refresh_tokens ( token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, access_token_id TEXT NOT NULL, session_id TEXT NOT NULL, -- the session expires_at TIMESTAMPTZ NOT NULL, used_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ ); CREATE INDEX refresh_tokens_session_id ON refresh_tokens (session_id); CREATE INDEX refresh_tokens_user_id ON refresh_tokens (user_id); ``` The dates are instants: on PostgreSQL, store them as `TIMESTAMPTZ`. A `TIMESTAMP` column has no time zone, and drivers like `pg` write dates in the time zone of the process: when the API does not run in UTC, the dates compared with `now()` in SQL are off by its offset. On MySQL, `TIMESTAMP` is stored in UTC. Expired tokens can be deleted by a scheduled job: `DELETE FROM refresh_tokens WHERE expires_at < now()`. ## An SQL data provider The data provider of the [Tasks API example](https://dotpress.dev/examples/tasks-api.md), on SQLite. The queries are the same on PostgreSQL or MySQL, with their placeholders: ```ts file="/../examples/tasks-api/src/features/auth/data-provider.ts" import type { DataProvider, RefreshTokenData } from '@dotpress/auth' import { get, run, type Database } from '../../db/database.ts' import type { UserRepository } from '../users/repository.ts' interface RefreshTokenRow { user_id: string access_token_id: string session_id: string expires_at: string used_at: string | null revoked_at: string | null } /** What @dotpress/auth reads and writes: users and refresh tokens. */ export const createDataProvider = ( db: Database, users: UserRepository ): DataProvider => ({ storeRefreshToken: async ({ tokenHash, userId, accessTokenId, sessionId, expiresAt, }) => { run( db, 'INSERT INTO refresh_tokens (token_hash, user_id, access_token_id, session_id, expires_at) VALUES (?, ?, ?, ?, ?)', tokenHash, userId, accessTokenId, sessionId, expiresAt.toISOString() ) }, findRefreshToken: async ( tokenHash ): Promise => { const row = get( db, 'SELECT * FROM refresh_tokens WHERE token_hash = ?', tokenHash ) return ( row && { userId: row.user_id, accessTokenId: row.access_token_id, sessionId: row.session_id, expiresAt: new Date(row.expires_at), isUsed: row.used_at !== null, usedAt: row.used_at === null ? null : new Date(row.used_at), revokedAt: row.revoked_at === null ? null : new Date(row.revoked_at), } ) }, markRefreshTokenAsUsed: async (tokenHash, usedAt) => { run( db, 'UPDATE refresh_tokens SET used_at = ? WHERE token_hash = ?', usedAt.toISOString(), tokenHash ) }, revokeUserTokens: async (userId) => { run( db, 'UPDATE refresh_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL', new Date().toISOString(), userId ) }, revokeSessionTokens: async (sessionId) => { run( db, 'UPDATE refresh_tokens SET revoked_at = ? WHERE session_id = ? AND revoked_at IS NULL', new Date().toISOString(), sessionId ) }, // A logout stops the access tokens of the session at once. isSessionRevoked: async (sessionId) => get( db, 'SELECT 1 FROM refresh_tokens WHERE session_id = ? AND revoked_at IS NOT NULL LIMIT 1', sessionId ) !== undefined, // On every authenticated request: becomes ctx.user. findUserById: (userId) => users.findById(userId), // At login: the username is the email address. findUserIdentifiers: (username) => users.findCredentials(username), updatePasswordHash: (userId, passwordHash) => users.setPasswordHash(userId, passwordHash), }) ``` `findUserById()` and `findUserIdentifiers()` come from the users repository of the app: the user table stays yours, with your columns. ## The type of the user The type of `ctx.user` is the `AuthUser` interface, which you complete once, with module augmentation: ```ts declare module '@dotpress/auth' { interface AuthUser { id: string email: string roles: string[] } } ``` `findUserById()` must return this type. See [Protecting routes](https://dotpress.dev/auth/protecting-routes.md#the-type-of-the-user). ## In tests A data provider over a `Map` is enough for the tests. The [Auth example](https://dotpress.dev/examples/auth.md) has one, in `src/store.ts`, used both by the app in development and by the tests. --- url: https://dotpress.dev/auth/protecting-routes.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Protecting routes The auth plugin reads the access token of every request. When it is valid, `ctx.user` and `ctx.auth` are set; otherwise, the request stays anonymous. Guards then decide which routes need a user. ## Guards ```ts import { createRouteGroup, defineRoute } from '@dotpress/core' import { requireAuth, requireRole } from '@dotpress/auth' declare module '@dotpress/auth' { interface AuthUser { id: string email: string roles: string[] } } // One route defineRoute({ path: '/profile', middlewares: [requireAuth], handler: ({ user }) => ({ email: user.email }), }) // Every route of a group const admin = createRouteGroup('/admin', [requireRole('admin')]) admin.defineRoute({ path: '/stats', handler: ({ user, auth }) => ({ admin: user.id, roles: auth.roles }), }) ``` | Guard | Without user | Without the right | | ----------------------------- | ------------ | ------------------------------------------------------------------------------------------------------- | | `requireAuth` | `401` | — | | `requireRole(...roles)` | `401` | `403` without one of the roles | | `requireClient(...clientIds)` | `401` | `403` when the token was issued for another client, see [Clients](https://dotpress.dev/auth/clients.md) | A `401` carries a `WWW-Authenticate: Bearer` header (RFC 6750), with `error="invalid_token"` when the request sent an expired, revoked or invalid token: the client knows it must refresh. Every `401` of the app gets this header, unless it already has one. The plugin reads the access token from the `Authorization: Bearer` header, then from its cookie in cookie mode. It never reads the request body: a route of the app can receive an `accessToken` field of its own, a third-party token for instance, without side effects. Guards are [typed middlewares](https://dotpress.dev/concepts/typing.md#middlewares-that-guarantee-a-value): in the routes using them, directly or through a group, `ctx.user` and `ctx.auth` are defined. They also declare the `bearerAuth` security scheme (`AUTH_SECURITY_SCHEMES`), without `meta.security`: the [OpenAPI document](https://dotpress.dev/services/openapi.md) marks these routes as secured, and the API reference shows an Authorize button. ## The type of the user `ctx.user` is what `dataProvider.findUserById()` returns. Describe it once: ```ts declare module '@dotpress/auth' { interface AuthUser { id: string email: string roles: string[] } } ``` `ctx.auth` holds the access token data: | Field | Content | | --------------- | ------------------------------------------------------------------------------------------- | | `userId` | The `sub` claim | | `sessionId` | The session (`sid` claim): see [Sessions and tokens](https://dotpress.dev/auth/sessions.md) | | `clientId` | The client application, with the `clients` setting | | `roles` | The roles of the user | | `accessTokenId` | The `jti` claim | | `username` | Only with the `usernameClaim` setting | | `claims` | Every claim of the token | ## Roles `requireRole()` checks the `roles` array of the user, or its `role` string. When roles are stored elsewhere, `getUserRoles(user)` returns them: ```ts createAuth({ // … getUserRoles: (user) => user.memberships.map((membership) => membership.role), }) ``` ## Routes for everyone, better for users Without a guard, a route serves anonymous and authenticated users alike: `ctx.user` is then `AuthUser | undefined`. ```ts defineRoute({ path: '/articles/:id', handler: async ({ req, user }) => { const article = await articles.find(req.params.id) return { ...article, bookmarked: user ? await bookmarks.has(user.id, article.id) : false } }, }) ``` ## Authentication is not authorization `requireAuth` proves who the user is, not what they may access. A route that reads `/invoices/:id` must still check that this invoice belongs to the user: otherwise, any user can read any invoice by changing the ID in the URL. It is the most common vulnerability of APIs ([OWASP API1: Broken Object Level Authorization](https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/)). ```ts import { createRouteGroup, notFoundError } from '@dotpress/core' import { requireAuth } from '@dotpress/auth' declare module '@dotpress/auth' { interface AuthUser { id: string } } declare const invoices: { find(id: string): Promise<{ id: string; customerId: string; total: number } | undefined> } const myInvoices = createRouteGroup('/invoices', [requireAuth]) myInvoices.defineRoute({ path: '/:id', handler: async ({ req, user }) => { const invoice = await invoices.find(req.params.id) // Not found, rather than forbidden: do not reveal that the invoice exists. if (!invoice || invoice.customerId !== user.id) return notFoundError('Invoice not found') return invoice }, }) ``` Check access in the query itself when you can (`WHERE id = ? AND customer_id = ?`), or in a middleware of the group for a whole resource: the [Tasks API example](https://dotpress.dev/examples/tasks-api.md) checks the membership of a project once, on the `/projects/:projectId` group. ## Reading the cookies yourself In cookie mode, a route of the app that reads the auth cookies itself must apply the same protection against cross-site requests as the plugin: `await auth.isCookieAuthenticationAllowed(ctx.req)`, which resolves to `false` for a request the plugin would refuse. See [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md). --- url: https://dotpress.dev/auth/sessions.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Sessions and tokens A session starts at login, and lives as long as its refresh tokens are renewed. This page covers the tokens, the lifetimes, the logout and the revocation of sessions. ## Access tokens Access tokens are JWTs following [RFC 9068](https://www.rfc-editor.org/rfc/rfc9068), signed with RS256: - the header has `typ: at+jwt`, so that another JWT signed with the same key (an ID token) is not accepted as an access token; - the claims are `iss`, `aud`, `sub`, `jti`, `iat`, `exp` and `auth_time`, plus `sid` (the session) and `client_id` (the client, with the [`clients` setting](https://dotpress.dev/auth/clients.md)); - the type, issuer, audience and client are checked on every request. They are valid **15 minutes** (`accessTokenTTL: '15m'`). A short lifetime limits the use of a leaked token, and of the tokens of a revoked session (see [Revocation](#revocation)). The username is not written in the token: it is often an email address, and a JWT is only encoded, readable by anyone who holds it, in logs and browsers. `sub` identifies the user, and `ctx.user` holds the profile. `usernameClaim: true` writes it if you need it. ## Refresh token rotation A refresh token is a random 128-byte value. Each refresh returns a new one and invalidates the previous one: **a refresh token is used once**. When a used refresh token comes back, it was probably stolen: the attacker and the legitimate client both hold it. The whole session is revoked, including the tokens the attacker obtained, `onRefreshTokenReuse` is called, and the request gets `401 INVALID_REFRESH_TOKEN`. ```ts createAuth({ // … onRefreshTokenReuse: ({ userId, sessionId, accessTokenId }) => { securityLog.warn({ userId, sessionId: sessionId }, 'Refresh token reused: session revoked') }, }) ``` Within 10 seconds after its first use (`refreshTokenReuseInterval`), a token presented again gets a new pair in the same session, like with Auth0 or Okta: concurrent refreshes from several tabs, and retries after a lost response, keep working. The interval is counted from the first use, and is not extended by later presentations: after it, the whole session is revoked, including the pairs issued within the interval. `refreshTokenReuseInterval: 0` disables it. ## Session lifetimes A session ends after one of two timeouts, numbers of seconds or [durations](https://dotpress.dev/concepts/options.md#durations) like `'14d'`: | Setting | Default | The session ends… | | ------------------------- | ------- | ---------------------------------------------- | | `session.idleTimeout` | 14 days | when it is not refreshed during this delay | | `session.absoluteTimeout` | none | this delay after login, even when it is active | ```ts session: { idleTimeout: '30d' } // consumer app: never logged out while active session: { idleTimeout: '1d', absoluteTimeout: '1d' } // backoffice: log in every day session: { idleTimeout: '7d', absoluteTimeout: '28d' } // log in every 4 weeks ``` With an absolute timeout, no token or cookie outlives the session, and the responses return `sessionExpiresAt`, so that the client can warn the user. The session starts at login (the `auth_time` claim): adding an absolute timeout also ends the sessions opened before, once they are older than it. An ended session makes `/auth/refresh` answer `401 EXPIRED_REFRESH_TOKEN`: the user logs in again. :::tip Applications with privileged users (backoffices, admin consoles) should have an absolute timeout: a session stolen from an admin then ends within the day. Each [client](https://dotpress.dev/auth/clients.md#session-lifetimes-per-client) can have its own lifetimes. ::: ## Logout `POST /auth/logout` revokes the **current session**: the other devices of the user stay logged in. With `{ "scope": "all" }`, it revokes every session of the user. - The session is identified by the refresh token (cookie, or `refreshToken` field), or by the access token. An expired access token does not prevent a logout. - The route is idempotent (RFC 7009): an unknown or missing token still answers `200` and clears the cookies, so that a client can always log out. Only `scope: 'all'` requires a valid access token or an active refresh token, and answers `401` without. - In cookie mode, the refresh token cookie of a cross-origin request gets `403 CROSS_ORIGIN_REQUEST`, as on `/auth/refresh`. Outside the routes, `auth.revokeSession(refreshToken, { scope })` does the same, and returns `{ userId, sessionId }`, or `undefined` when nothing was revoked. `ctx.auth.sessionId` lets an app list the sessions of a user, and log out one device with `dataProvider.revokeSessionTokens(sessionId)`. ## Revoke every session after a password change :::warning When a password is changed or reset, revoke every session of the user: a stolen session must not survive the change. ::: From the [Auth example](https://dotpress.dev/examples/auth.md): ```ts await store.users.setPasswordHash(user.id, await auth.hashPassword(req.body.newPassword)) // A stolen session must not survive a password change. await auth.revokeUserSessions(user.id) ``` Do the same when an account is disabled, or when the email address changes. ## Revocation The access tokens are verified without a database lookup: revoking a session does not invalidate the access tokens already issued. | Event | Refresh | Access tokens already issued | | ----------------------------------------------------------------- | -------------------------------- | --------------------------------------------------------------------------------- | | Account deleted or disabled (`findUserById` returns `undefined`) | rejected, the session is revoked | rejected at once | | Logout, `scope: 'all'`, refresh token reuse, `revokeUserTokens()` | rejected | valid until they expire (15 minutes), or rejected at once with `isSessionRevoked` | ### Immediate revocation Implement the optional `isSessionRevoked(sessionId)` method of the data provider: the access tokens of a revoked session are rejected at once (`SESSION_REVOKED`: the request stays anonymous). It costs one lookup per authenticated request, in a store shared by every instance of the API. The revoked sessions are already in the refresh tokens table: ```ts isSessionRevoked: async (sessionId) => { const { rowCount } = await pool.query( 'SELECT 1 FROM refresh_tokens WHERE session_id = $1 AND revoked_at IS NOT NULL LIMIT 1', [sessionId] ) return (rowCount ?? 0) > 0 // rowCount: number | null } ``` For faster lookups, record the revoked sessions in Redis when revoking them, for `accessTokenTTL` only: afterwards, every access token of the session has expired. ```ts const ACCESS_TOKEN_TTL = 900 // same as accessTokenTTL const markRevoked = (sessionIds: string[]) => Promise.all(sessionIds.map((id) => redis.set(`revoked-session:${id}`, '1', { EX: ACCESS_TOKEN_TTL }))) const dataProvider: DataProvider = { // … revokeSessionTokens: async (sessionId) => { await db.refreshTokens.revokeSession(sessionId) await markRevoked([sessionId]) }, revokeUserTokens: async (userId) => { const sessionIds = await db.refreshTokens.activeSessionIds(userId) await db.refreshTokens.revokeUser(userId) await markRevoked(sessionIds) }, isSessionRevoked: async (sessionId) => (await redis.exists(`revoked-session:${sessionId}`)) === 1, } ``` An error thrown by `isSessionRevoked` fails closed: the request stays anonymous, and a warning is logged. Do not cache the answer in the memory of each instance: a revocation would only be seen by the instance that made it. --- url: https://dotpress.dev/auth/cookies.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Cookie mode and CSRF For browser applications, keep the tokens in `httpOnly` cookies. The JavaScript of the page never sees them: a script injected in the page (XSS) cannot steal them, while a token stored in `localStorage` or in memory can be read and sent anywhere. ## Enable it ```ts const auth = createAuth({ // … cookies: { enabled: true, accessTokenInCookie: true }, }) ``` The browser logs in with `mode: 'cookie'`, and sends the cookies with each request: ```ts // In the browser await fetch('https://api.example.com/auth/login', { method: 'POST', credentials: 'include', // only needed when the API is on another origin headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username, password, mode: 'cookie' }), }) const profile = await fetch('https://api.example.com/profile', { credentials: 'include' }) ``` A login without `mode: 'cookie'` gets the tokens in the body, as usual: the same API serves the browser and the mobile application. ## The modes | Configuration | Cookies | Body | | ------------------------------------------------------- | --------------------------- | ---------------------------------------------------- | | Body mode (default) | — | `accessToken`, `refreshToken` | | `cookies: { enabled: true }` | refresh token | `accessToken`, to send in the `Authorization` header | | `cookies: { enabled: true, accessTokenInCookie: true }` | refresh token, access token | no token | A token set as a cookie is never returned in the body. Prefer the last mode: with the access token in the body, the page has to keep it in JavaScript. ## Restoring the session When the page loads, it does not know whether the user is logged in: the cookies are out of its reach. `POST /auth/restore` answers with the user and the expiration of the session, or `401`: ```ts const res = await fetch('/auth/restore', { method: 'POST', credentials: 'include' }) const session = res.ok ? await res.json() : undefined // { userId, user, expiresIn, expiresAt } ``` Then refresh before `expiresAt` with `POST /auth/refresh`: the cookies are renewed. `/auth/restore` requires `cookies.accessTokenInCookie`. ## The cookies | Cookie | Default name | Path | Attributes | | ------------- | --------------------------------- | ------------------------- | --------------------------------------- | | Access token | `__Host-dotpress_access_token` | `/` | `HttpOnly`, `Secure`, `SameSite=Lax` | | Refresh token | `__Secure-dotpress_refresh_token` | the auth routes (`/auth`) | `HttpOnly`, `Secure`, `SameSite=Strict` | - **The prefixes** protect the cookies: `__Host-` (secure, path `/`, no `domain`) prevents a subdomain or an insecure page from overwriting the cookie, `__Secure-` prevents an insecure page from overwriting it. - **The refresh token is only sent to the auth routes**, never to the rest of the API, and never with a navigation from another site (`SameSite=Strict`). - Its path follows the prefix of the plugin and the [base path](https://dotpress.dev/routing/http-options.md#base-path) of the app. `cookies.refreshTokenPath` forces another one. - **Both cookies live as long as the refresh token**, not `accessTokenTTL`: a refresh needs the access token, even expired. - **The path** of the refresh token cookie must be the browser path of the auth routes: with a wrong path, the browser does not send it, and refreshes fail with `401 NO_TOKENS_PROVIDED`. It is set by `authPlugin()`, after the `basePath` or `publicBasePath` of the app; without the plugin, it is `/auth`. An auth service serves one path: create one per app when several apps serve the auth routes under different paths. - **Names**: without `secure`, the default names have no prefix. Custom names (`accessTokenName`, `refreshTokenName`) are kept as is, and checked at startup: a `__Host-` or `__Secure-` name without the attributes it requires would be silently rejected by browsers. - `secure` is `true` by default. Chrome and Firefox accept secure cookies on `http://localhost`, Safari does not: with Safari, develop over HTTPS (a local certificate, made with [mkcert](https://github.com/FiloSottile/mkcert) for instance), or set `secure: false` in development only. The default names then have no prefix. Set `secure: false` as well for another plain HTTP host in development. Every setting of the cookie mode is listed in the [Auth reference](https://dotpress.dev/reference/auth.md#cookie-settings). ## Protection against cross-site request forgery The browser attaches cookies to every request, including the ones that another site makes it send: that is cross-site request forgery (CSRF). In cookie mode, the plugin checks where the requests authenticated by a cookie come from, with the headers set by the browser (`Sec-Fetch-Site`, then `Origin` for older browsers), as the OWASP recommends. Clients need no CSRF token. - Requests from the origin of the API are accepted, as well as requests without these headers (clients that are not browsers). - Requests from another origin, **including another subdomain of the same site**, are accepted only from **trusted origins**. - Otherwise, the access token cookie is ignored (the request is anonymous, and a warning is logged), and `/auth/refresh`, `/auth/restore` and `/auth/logout` answer `403 CROSS_ORIGIN_REQUEST`. - `GET`, `HEAD` and `OPTIONS` requests are not checked: they must not change data. Never change data in a `GET` route. - Requests authenticated by the `Authorization` header are not checked: another site cannot set it. ### Trusted origins By default, the trusted origins are those of the [`cors` option](https://dotpress.dev/routing/http-options.md#cors) of the app, when it allows credentials. A front-end on another origin needs this CORS configuration anyway to use the cookies: ```ts await createApp({ adapter, cors: { origin: ['https://app.example.com'], credentials: true }, plugins: [authPlugin(auth)], }) ``` `cookies.trustedOrigins` replaces them (`[]` trusts no other origin): ```ts cookies: { enabled: true, accessTokenInCookie: true, trustedOrigins: ['https://app.example.com'] } ``` For older browsers without `Sec-Fetch-Site`, the `Origin` is compared with the `Host` header: behind a proxy, forward the original `Host`, or list the origin in `trustedOrigins`. ### Routes that read the cookies A route of your app that reads the auth cookies itself applies the same check with `await auth.isCookieAuthenticationAllowed(ctx.req)`: it returns a promise, so never test it without `await`. ## An application on another site The defaults suit an application served from the same site as the API (`app.example.com` and `api.example.com`). For an application on another site (`example.app` for `api.example.com`), the cookies need `sameSite: 'none'`: they are then sent with cross-site requests, and the CSRF protection above is what keeps them safe. Prefer serving the application and the API from the same site when you can. :::tip Coming from v1 The tokens set as cookies are no longer returned in the body, the cookies get the `__Host-` and `__Secure-` prefixes, the refresh token cookie is restricted to the auth routes, and the cookie mode is protected against CSRF. To keep the sessions of your users when upgrading, see [Migrate from v1](https://dotpress.dev/reference/migrate-from-v1.md). ::: --- url: https://dotpress.dev/auth/clients.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Clients When one API serves several applications, such as a customer app and a backoffice, declare them as clients. Each token then records the application it was issued for, and routes can be restricted to the tokens of one application. ```ts const auth = createAuth({ // … clients: { allowed: ['app', 'backoffice'], required: true, // clientId required at login isUserRoleAllowed: ({ role, clientId }) => clientId !== 'backoffice' || role === 'admin', }, }) createRouteGroup('/backoffice', [requireClient('backoffice'), requireRole('admin')]) ``` - The `clientId` of the login must be one of `allowed`: otherwise `400`. - `isUserRoleAllowed({ userId, role, clientId })` decides whether a user may get a token for this client: here, only admins get backoffice tokens. `role` is the one returned by `findUserIdentifiers()`. - The token carries a `client_id` claim, exposed as `ctx.auth.clientId`. - `requireClient(...clientIds)` answers `403` to the tokens of other clients. - Removing a client from `allowed` rejects its tokens, and its sessions can no longer be refreshed. :::warning What a client ID proves The client ID is declared by the caller: anyone can send `clientId: 'backoffice'`. A `client_id` claim does not prove which application sends a request; it means that the token was issued under the policy of that client (`isUserRoleAllowed`). `requireClient()` keeps the tokens of one application away from the routes of another: combine it with `requireRole()`. ::: ## Session lifetimes per client Each client can have its own [session lifetimes](https://dotpress.dev/auth/sessions.md#session-lifetimes): ```ts const DAY = 24 * 60 * 60 clients: { allowed: ['app', 'backoffice'], sessions: { backoffice: { idleTimeout: DAY, absoluteTimeout: DAY } }, } ``` Customers stay logged in while they use the app; admins log in every day. Each timeout of a client overrides the global one, which applies when it is not set; an explicit `absoluteTimeout: undefined` removes the global absolute timeout for this client. ## Without the setting Without `clients`, the `clientId` sent at login is only reported to the login events (`onLoginSuccess`, `onLoginFailed`), and not written in the token. --- url: https://dotpress.dev/auth/passwords.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Passwords and brute force ## Hashing Passwords are hashed with bcrypt, with a cost of **12** by default (`passwordHashRounds`), like Rails and Laravel: about 200 ms per login on a recent laptop. Measure it on your servers: the cost slows down an attacker who stole the hashes, and your logins too. ```ts const passwordHash = await auth.hashPassword(password) // at sign-up const valid = await auth.verifyPassword(password, passwordHash) ``` `generatePasswordHash(password, { rounds })` hashes without an auth service, in a script that creates accounts. Like `hashPassword()`, it throws a `RangeError` beyond 72 bytes. ### The 72-byte limit bcrypt reads the first 72 bytes of a password, in UTF-8, and ignores the rest. Rather than truncating silently, `hashPassword()` throws a `RangeError` for longer passwords. Check the length in the schemas of sign-up and password change, so that users get a validation error: ```ts import { isPasswordTooLong } from '@dotpress/auth' import { z } from 'zod' const Password = z .string() .min(12) .refine((password) => !isPasswordTooLong(password), 'Password too long') ``` 72 bytes are 72 ASCII characters, fewer with accents or emojis (`é` takes 2 bytes). Logins are not limited: passwords created before the check keep working. ### Choosing the rules Follow the NIST guidelines (SP 800-63B): require long passwords rather than complex ones (no forced mix of digits and symbols, no periodic change), accept spaces and any character, and reject passwords known to have leaked, for instance with the k-anonymity API of [Have I Been Pwned](https://haveibeenpwned.com/API/v3#PwnedPasswords). ### Raising the cost Implement the optional `updatePasswordHash(userId, passwordHash)` method of the data provider: at each successful login, a hash with another cost than `passwordHashRounds` is replaced by a new one, computed from the password just verified. Raising the cost then upgrades the users as they log in. An error of the method is logged, and does not fail the login. While hashes with the previous cost remain, their accounts answer faster than unknown usernames, which reveals that they exist (see below). Accept it during the migration, or keep `passwordHashRounds` at the cost of your hashes (`10` for hashes created by Dotpress 1). ## Account enumeration A failed login gets the same `401 INVALID_LOGIN` response, in the same time, whether the username is unknown, the account has no password, or the password is wrong: unknown users are checked against a dummy hash, computed at startup with `passwordHashRounds`. An attacker cannot learn which usernames exist. Two things keep it effective: - `passwordHashRounds` must match the cost of the hashes in your database; - `onLoginFailed` must do the same work whatever the `errorType`: do not update the user row only on `invalid_password`. Apply the same care to your own routes: a sign-up that answers "email already used", or a password reset that answers "unknown email", reveals the accounts. Answer the same way, and send an email instead. ## Brute force protection Failed logins are throttled by default, before the password is checked: | Counter | Default | Against | | --------------------- | ------------ | -------------------------------------------------------------------- | | username + IP address | 5 per minute | brute force from one client, without letting others lock the account | | username | 100 per hour | distributed brute force on one account | Over a limit, the login answers `429 TOO_MANY_LOGIN_ATTEMPTS` with a `Retry-After` header, and `onLoginFailed` gets `errorType: 'too_many_attempts'`. Attempts are counted whether the account exists or not, so a `429` reveals nothing. A successful login clears the counter of the client. Usernames are normalized (letter case, spaces), and the keys of the counters are hashed. ```ts createAuth({ loginThrottle: { store: redisStore, // see below limits: { usernameAndIp: { max: 10, window: 60 }, username: false }, }, }) ``` :::warning Behind a proxy The IP address comes from the HTTP server. Behind a load balancer or a reverse proxy, configure the server to trust the proxy headers (Express `trust proxy`, Fastify `trustProxy`, Hono `getIp`): otherwise every client shares the address of the proxy, and one attacker locks out everyone on a username. See [Client IP address](https://dotpress.dev/routing/http-options.md#client-ip-address-behind-a-proxy). ::: ### A shared store The default store, `createMemoryRateLimitStore()`, keeps the counters in memory: with several instances of the API, each one counts on its own. Use a shared store, which increments a counter atomically. `RateLimitStore` is the contract of `@dotpress/core`, so a store can serve other rate limits of your app too: ```ts import type { RateLimitStore } from '@dotpress/core' // Redis (ioredis) const redisStore: RateLimitStore = { async increment(key, windowSeconds) { const results = await redis .multi() .set(key, 0, 'EX', windowSeconds, 'NX') // starts a window .incr(key) .pttl(key) .exec() return { count: Number(results![1]![1]), resetAt: new Date(Date.now() + Number(results![2]![1])), } }, reset: async (key) => void (await redis.del(key)), } ``` ```sql -- PostgreSQL: rate_limits (key TEXT PRIMARY KEY, count INT, reset_at TIMESTAMPTZ) INSERT INTO rate_limits (key, count, reset_at) VALUES ($1, 1, now() + make_interval(secs => $2)) ON CONFLICT (key) DO UPDATE SET count = CASE WHEN rate_limits.reset_at <= now() THEN 1 ELSE rate_limits.count + 1 END, reset_at = CASE WHEN rate_limits.reset_at <= now() THEN EXCLUDED.reset_at ELSE rate_limits.reset_at END RETURNING count, reset_at; ``` `loginThrottle: false` disables the protection, only when the infrastructure (an API gateway, a WAF) already limits `/auth/login`. ### Custom policies `beforeLogin` runs after the throttle and before the password check: return an error to reject the attempt (a blocked address, a CAPTCHA required after some failures…). ```ts createAuth({ beforeLogin: async ({ username, ipAddress, clientId, req }) => { if (await blockedAddresses.has(ipAddress)) return forbiddenError('LOGIN_BLOCKED') }, }) ``` ## Login events `onLoginSuccess` and `onLoginFailed` receive each attempt, with the username, the client and the IP address: feed your security logs and alerts with them. --- url: https://dotpress.dev/auth/keys.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Keys and rotation Access tokens are signed with an RSA private key (RS256), and verified with its public key. Whoever holds the private key can sign tokens for any user: protect it like your database password, and rotate it. ## Generate a key pair ```sh openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem # PKCS#8 openssl pkey -in private.pem -pubout -out public.pem # SPKI ``` `@dotpress/auth` expects PEM keys in the PKCS#8 (`BEGIN PRIVATE KEY`) and SPKI (`BEGIN PUBLIC KEY`) formats. `createApp()` fails when the public key does not match the private key, and explains how to convert PKCS#1 keys (`BEGIN RSA PRIVATE KEY`): ```sh openssl pkcs8 -topk8 -nocrypt -in private.pem -out private.pkcs8.pem openssl rsa -RSAPublicKey_in -in public.pem -pubout -out public.spki.pem ``` ## Store them - Keep the private key in a secret manager (AWS Secrets Manager, Vault, the secrets of your platform), given to the app as an environment variable. Never in the repository, never in a container image. - Use **one key pair per environment**: a token of staging must not open production. The `issuer` setting, checked on every request, adds a second barrier: one value per environment and application. - Platforms that store a PEM in one line escape its line breaks: restore them with `value.replaceAll('\\n', '\n')`. - In development, a key pair can be generated at startup (`generateKeyPairSync()` of `node:crypto`), as the [Auth example](https://dotpress.dev/examples/auth.md) does: the tokens then stop working at each restart. ## Rotate them Rotate the signing keys on a schedule, every few months for instance, and at once after a suspected leak. A scheduled rotation logs nobody out: the old public key keeps verifying the tokens it signed, while the new private key signs the new ones. ```ts keys: { privateKey: env.JWT_PRIVATE_KEY, // the new pair publicKey: env.JWT_PUBLIC_KEY, additionalPublicKeys: [env.JWT_PREVIOUS_PUBLIC_KEY], // the old public key } ``` | Step | Configuration | | -------------------------------------------------------------------------- | --------------------------------------------------------- | | 1. Announce the new key, when several instances deploy one after the other | old pair active, new public key in `additionalPublicKeys` | | 2. Switch | new pair active, old public key in `additionalPublicKeys` | | 3. After `session.idleTimeout` (14 days by default) | remove the old public key | Keep the old public key for the inactivity timeout of the sessions, not only for the lifetime of the access tokens: a refresh verifies the signature of the expired access token, so a client that was inactive for a week still presents a token of the old key. Each token carries a `kid` header, the thumbprint of its public key (RFC 7638), or `keys.kid`: the right key is picked among the configured ones only. Tokens without `kid`, issued by Dotpress 1, are tried with every configured key. ### After a compromise Configure the new pair alone, without `additionalPublicKeys`: every token of the old key, including the forged ones, is rejected at once. Every user logs in again; that is the price of a leaked key. ## Publish the public keys Other services can verify the tokens of your API themselves: ```ts authPlugin(auth, { jwks: true }) // GET /.well-known/jwks.json, cached 5 minutes ``` They follow the rotations through the key set, for instance with `createRemoteJWKSet()` of [jose](https://github.com/panva/jose). They must check the issuer, the audience and the `at+jwt` type, like Dotpress does. `auth.getJwks()` returns the same key set. --- url: https://dotpress.dev/auth/security.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Security checklist `@dotpress/auth` is secure by default: rotating refresh tokens, short-lived access tokens, throttled logins, `httpOnly` cookies protected against CSRF. Some decisions remain yours. Check this list before going to production. ## Keys and tokens - [ ] The private key is stored in a secret manager, never in the repository or an image. [Keys](https://dotpress.dev/auth/keys.md#store-them) - [ ] Each environment has its own key pair, and its own `issuer`. [Keys](https://dotpress.dev/auth/keys.md#store-them) - [ ] The keys are rotated on a schedule, and you know how to rotate them after a leak. [Rotation](https://dotpress.dev/auth/keys.md#rotate-them) - [ ] `accessTokenTTL` stays short: 15 minutes by default. [Access tokens](https://dotpress.dev/auth/sessions.md#access-tokens) - [ ] The username is not written in the tokens, unless needed (`usernameClaim`). [Access tokens](https://dotpress.dev/auth/sessions.md#access-tokens) ## Browsers - [ ] Browser applications use the cookie mode with `accessTokenInCookie`: no token is readable by the JavaScript of the page. [Cookie mode](https://dotpress.dev/auth/cookies.md) - [ ] The API is served over HTTPS only, and the cookies stay `secure`. [Cookies](https://dotpress.dev/auth/cookies.md#the-cookies) - [ ] CORS lists the trusted origins explicitly, without `'*'` or a function accepting any origin. [CORS](https://dotpress.dev/routing/http-options.md#cors) - [ ] No `GET` route changes data: they are not checked against cross-site requests. [CSRF](https://dotpress.dev/auth/cookies.md#protection-against-cross-site-request-forgery) - [ ] Mobile applications keep their tokens in the secure storage of the platform (Keychain, Keystore), never in plain files. ## Sessions - [ ] Every session is revoked when a password is changed or reset, and when an account is disabled. [Password change](https://dotpress.dev/auth/sessions.md#revoke-every-session-after-a-password-change) - [ ] `findUserById()` returns `undefined` for deleted, disabled and banned accounts. [Data provider](https://dotpress.dev/auth/data-provider.md#the-methods) - [ ] Privileged applications (backoffice) have an absolute session timeout. [Session lifetimes](https://dotpress.dev/auth/sessions.md#session-lifetimes) - [ ] Sensitive applications reject the tokens of a revoked session at once, with `isSessionRevoked`. [Revocation](https://dotpress.dev/auth/sessions.md#immediate-revocation) - [ ] `onRefreshTokenReuse` raises an alert: a reused refresh token means a stolen session. [Rotation](https://dotpress.dev/auth/sessions.md#refresh-token-rotation) ## Passwords and logins - [ ] Passwords are long (12 characters or more), without composition rules, and checked against known leaks. [Rules](https://dotpress.dev/auth/passwords.md#choosing-the-rules) - [ ] The schemas of sign-up and password change reject passwords over 72 bytes (`isPasswordTooLong`). [72-byte limit](https://dotpress.dev/auth/passwords.md#the-72-byte-limit) - [ ] The bcrypt cost (`passwordHashRounds`) is measured on your servers, and matches your stored hashes. [Hashing](https://dotpress.dev/auth/passwords.md#hashing) - [ ] With several instances, the login throttle uses a shared store. [Shared store](https://dotpress.dev/auth/passwords.md#a-shared-store) - [ ] Behind a proxy, the server trusts the proxy headers, so that each client has its own IP address. [Proxy](https://dotpress.dev/auth/passwords.md#brute-force-protection) - [ ] Sign-up and password reset answer the same way whether the account exists or not. [Enumeration](https://dotpress.dev/auth/passwords.md#account-enumeration) ## Authorization - [ ] Every route reading or changing a resource checks that the user may access **this** resource, not only that a user is logged in. [Authorization](https://dotpress.dev/auth/protecting-routes.md#authentication-is-not-authorization) - [ ] Response schemas list the returned fields: password hashes and internal fields never reach the client. [Validation](https://dotpress.dev/routing/validation.md#validating-the-response) - [ ] The routes of a backoffice require its client and a role (`requireClient()`, `requireRole()`). [Clients](https://dotpress.dev/auth/clients.md) ## The app - [ ] `exposeErrors` is disabled in production. [Errors](https://dotpress.dev/routing/errors.md#details-in-development) - [ ] Unexpected errors are reported (`onError`), and login failures are logged (`onLoginFailed`). [Login events](https://dotpress.dev/auth/passwords.md#login-events) - [ ] Dependencies are kept up to date, and the security advisories of Dotpress are followed: see the [security policy](https://github.com/dotpressjs/dotpress/security/policy). --- url: https://dotpress.dev/services/openapi.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # OpenAPI and API docs `@dotpress/openapi` builds an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) document from the routes of your app, and serves an interactive API reference with [Scalar](https://scalar.com). No annotation: the paths, parameters, bodies and responses come from the Zod schemas of the routes, and the security from their middlewares. The documentation cannot drift from the code. ```sh [npm] npm install @dotpress/openapi ``` ```sh [yarn] yarn add @dotpress/openapi ``` ```sh [pnpm] pnpm add @dotpress/openapi ``` ```sh [bun] bun add @dotpress/openapi ``` ```sh [deno] deno add npm:@dotpress/openapi ``` ```ts import { openapiPlugin } from '@dotpress/openapi' const app = await createApp({ adapter, plugins: [ authPlugin(auth), openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0' } }), ], }) // GET /openapi.json: the document // GET /docs: the API reference ``` The document is generated once, when the app is created. ## What is documented | Source | OpenAPI | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `path` (`/users/:id`) | the path (`/users/{id}`), with the base path of the app | | `schema.params`, `schema.query` | path and query parameters. Path parameters without schema are strings. | | `schema.body` | the JSON request body, required unless the schema is optional | | `schema.files` | a `multipart/form-data` body, with the `body` fields | | `schema.response`, `status` | the success response (`200` by default) | | `meta.responses` | other responses | | middlewares, `meta.security` | the security requirements | | `meta.summary`, `description`, `tags`… | the operation. `meta.hidden` excludes the route. | | — | the standard errors: `400` for routes with request schemas, `401` and `403` for secured routes, `500`, with the `DotpressError` schema | Request schemas are documented as the client sends them (`z.coerce.number()` is a number, a field with a default is optional), response schemas as the API returns them. Dates are ISO 8601 strings. ## Describe the routes ```ts defineRoute({ method: 'post', path: '/tasks', status: 201, schema: (z) => ({ body: TaskInput, response: Task }), meta: { summary: 'Create a task', description: 'The task is added to the project of the current user.', tags: ['tasks'], responses: { 409: 'A task with this title already exists' }, }, handler, }) ``` `meta.responses` documents the responses the schemas do not describe: errors returned by the handler, or bodies that are not JSON. An entry is a description, or an object with `description`, `schema` and `contentType`: ```ts meta: { responses: { 200: { description: 'CSV export', contentType: 'text/csv' }, 404: 'Member not found', 409: { description: 'Already exported', schema: ExportStatus }, }, } ``` An entry replaces the generated response of the same status. ## Reusable schemas A Zod schema with an identifier is declared once in `components/schemas`, and referenced by the routes: ```ts const Task = z .object({ id: z.uuid(), title: z.string(), done: z.boolean() }) .meta({ id: 'Task', description: 'A task to do' }) ``` When the input and output of a schema differ (defaults, transforms, the `additionalProperties: false` of the output of objects), the request side gets an `Input` variant: `Task` and `TaskInput`. Two different schemas with the same identifier fail the generation. Recursive schemas need an identifier. ## Security A route is secured by the security schemes its middlewares declare, including group and global middlewares. `requireAuth`, `requireRole()` and `requireClient()` of `@dotpress/auth` declare `bearerAuth`, and the auth plugin declares the scheme: the API reference shows an Authorize button, and the secured routes a lock. Your own middlewares declare theirs: ```ts const requireApiKey = defineMiddleware(checkApiKey, { security: ['apiKey'] }) openapiPlugin({ info, securitySchemes: { apiKey: { type: 'apiKey', in: 'header', name: 'x-api-key' } }, }) ``` `meta.security` overrides the schemes of a route, and `[]` marks it as public. A scheme used by a route but not declared is reported as a warning, like a schema without JSON representation: the plugin logs them with its logger. ## Options | Option | Default | Description | | ----------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `info` | — | **Required.** `title`, `version`, and the other fields of the OpenAPI `info` object. | | `servers` | the public base path of the app | The servers of the document. | | `tags` | — | Descriptions of the tags used by the routes. | | `externalDocs` | — | A link to external documentation. | | `securitySchemes` | — | Security schemes, added to those of the plugins. | | `path` | `/openapi.json` | The path of the document. | | `ui` | `{ path: '/docs' }` | The Scalar page: `path`, `title`, `configuration`, `cdnUrl`, `integrity`. `false` serves the document only. | | `middlewares` | `[]` | Middlewares of the document and page routes, for instance to restrict them. | :::tip Public or private documentation? The document lists every route of the API, with its parameters. For an internal API, protect it with `middlewares: [requireRole('admin')]`, or serve it in development only. ::: ## The API reference The page loads a pinned version of Scalar from jsDelivr, checked with Subresource Integrity. It is neutral by default (`SCALAR_NEUTRAL_CONFIGURATION`): no telemetry, no AI agent or MCP integration, no developer toolbar, no link to the Scalar client, system fonts, and no "Powered by Scalar" link. `ui.configuration` overrides these settings with the [Scalar configuration](https://guides.scalar.com/scalar/scalar-api-references/configuration), and its `customCss` is appended. `cdnUrl` hosts the script yourself. ### Content Security Policy The page sets its own Content Security Policy: the Scalar script, its inline script (allowed by its hash), styles, and requests to the document and to the `servers` of the document, for "Try it". Nothing else is loaded. This policy replaces the one that a security middleware sets for the whole app before the routes, such as `helmet()` on Express or `@fastify/helmet`, which would block the page. - `ui.contentSecurityPolicy` adds sources to the directives, for instance an image host used in your descriptions: `{ 'img-src': ['https://cdn.example.com'] }`. `false` sets no policy. - A middleware that writes its headers after the route replaces the policy of the page, and blocks it: the `secureHeaders()` middleware of Hono, with its `contentSecurityPolicy` option. Leave the page out of it, by registering the middleware on the paths of your API only. ## The document in CI `dotpress-openapi` writes the document without starting the server, to commit it, check its changes in pull requests, or generate clients. Point it to the entry point of your server: ```sh npx dotpress-openapi src/server.ts --out openapi.json ``` The command imports the module like `node src/server.ts`, with two differences: `app.listen()` starts no server, and what the module prints goes to the standard error. It documents the app that the module creates, then closes it (`onClose` hooks). Code that runs at startup still runs: the configuration is read and validated, and connections opened by your code are closed when the command exits. The module can also be: - the entry point of [AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md): the factory of `createLambdaHandler()` is called right away; - a module that exports the app, or a function creating it, like `src/app.ts`. The function receives an adapter that mounts nothing, as its single argument: `createTasksApp(adapter)` and `createTasksApp({ adapter })` both work. `--export` chooses the export, when the module does not create the app itself: `default`, or the only exported function, by default. - With `openapiPlugin()`, its document is used as is. Otherwise, the document is generated with `--title` and `--api-version`, or the name and version of the `package.json` of the current directory. - Without `--out`, the document is printed on the standard output. Warnings and errors go to the standard error, with a non-zero exit code on failure. - TypeScript modules are loaded with the type stripping of Node.js 22.18 or later. Otherwise, point to the compiled module, or run the command with `NODE_OPTIONS="--import tsx"`. In code, the plugin returns the document with `getDocument()`, once the app is created: ```ts const docs = openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0' } }) const app = await createApp({ adapter: honoAdapter(), plugins: [docs] }) const document = docs.getDocument() ``` `generateOpenApi(app, options)` returns the document in code, with the options of the plugin except `path`, `ui` and `middlewares`, plus `onWarning` (`console.warn` by default): ```ts import { generateOpenApi } from '@dotpress/openapi' const document = generateOpenApi(app, { info: { title: 'Tasks API', version: '1.0.0' } }) ``` ## Example Every example serves its document and reference. The [Express example](https://dotpress.dev/examples/express.md) shows reusable schemas and documented errors; the [Auth example](https://dotpress.dev/examples/auth.md), secured routes. Every option, and the command: see the [OpenAPI reference](https://dotpress.dev/reference/openapi.md). --- url: https://dotpress.dev/services/mailer.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Emails `@dotpress/mailer` sends typed, multilingual emails: templates written in [MJML](https://mjml.io) or HTML, with shared layouts, data checked by a Zod schema, and interchangeable providers (SMTP, Amazon SES, Resend, SendGrid, Postmark…). It works in a route, a worker or a script. ```sh [npm] npm install @dotpress/mailer zod mjml ``` ```sh [yarn] yarn add @dotpress/mailer zod mjml ``` ```sh [pnpm] pnpm add @dotpress/mailer zod mjml ``` ```sh [bun] bun add @dotpress/mailer zod mjml ``` ```sh [deno] deno add npm:@dotpress/mailer npm:zod npm:mjml ``` `mjml` is only needed for MJML templates: with `html` templates, it is never loaded. `@dotpress/core` is only needed for the plugin. ## A layout and a template A layout holds what every email shares; a template, the content of one email, in each language. From the [Mailer example](https://dotpress.dev/examples/mailer.md): ```ts file="/../examples/mailer/src/mails/layout.ts" import { defineLayout } from '@dotpress/mailer' /** * Shared by every email: the templates provide the `` elements, * placed in `content`. `t()` reads the translations of the layout. */ export const baseLayout = defineLayout({ translations: { footer: { en: 'Example Inc. · 1 Example Street, Example City', fr: 'Example SAS · 1 rue de l’Exemple, Exempleville', }, }, mjml: ({ t, content, locale }) => ` Example ${content} ${t('footer')} `, }) ``` ```ts file="/../examples/mailer/src/mails/contact-received.ts" import { defineTemplate } from '@dotpress/mailer' import { z } from 'zod' import { baseLayout } from './layout.ts' /** * Sent to the visitor, in their language. It does not repeat the message: * otherwise, anyone could send any text to any address through the form. */ export const contactReceived = defineTemplate({ name: 'contactReceived', layout: baseLayout, schema: z.object({ name: z.string() }), // {{name}} is inserted by Mustache, after the translations. subject: { en: 'We received your message, {{name}}', fr: 'Nous avons bien reçu votre message, {{name}}', }, translations: { greeting: { en: 'Hello {{name}},', fr: 'Bonjour {{name}},' }, body: { en: 'Thank you for contacting us. We will answer within two business days.', fr: 'Merci de nous avoir contactés. Nous vous répondrons sous deux jours ouvrés.', }, signature: { en: 'The Example team', fr: 'L’équipe Example' }, }, mjml: ({ t }) => ` ${t('greeting')} ${t('body')} ${t('signature')} `, }) ``` The data is checked by TypeScript when you send, and by the schema at runtime: ```ts import { createMailer, createMemoryProvider, defineTemplate } from '@dotpress/mailer' import { z } from 'zod' const mailer = createMailer({ provider: createMemoryProvider(), from: 'noreply@example.com' }) const invoiceReady = defineTemplate({ name: 'invoiceReady', schema: z.object({ number: z.string(), amount: z.string(), url: z.url() }), subject: 'Your invoice {{number}}', html: '

Your invoice of {{amount}} is ready: download it.

', }) await mailer.send(invoiceReady, { to: 'ada@example.com', data: { number: 'F-2026-001', amount: '€42.00' }, // Error: `url` is missing }) ``` ## How a template is rendered 1. **Translations**: the template function runs with `t()`, which returns the texts of the locale. The layout receives the result as `content`. 2. **MJML** compiles it to HTML. This step only depends on the template and the locale: it is cached. 3. **Mustache** inserts the data (`{{name}}`) in the HTML, the subject and the text version. Translations can use the data too (`{ en: 'Hello {{name}}' }`), and contain HTML. A layout and its templates use the same format, MJML or HTML; the `t()` of a layout only reads its own translations. Without a `schema`, a template accepts no data; with one, the parsed data is rendered. | Syntax | HTML version | Subject and text version | | ------------- | ------------ | ------------------------ | | `{{value}}` | escaped | as is | | `{{{value}}}` | as is | as is | :::warning Escaping Use `{{value}}` for any data, and in particular for user input: it is HTML-escaped. Keep `{{{url}}}` for the URLs built by your app. `/`, `=` and `` ` `` are not escaped, so that links work in every email client. ::: Without a `text` source, the text version is converted from the HTML: lines wrapped at 78 characters, links followed by their URL, data tables in columns, images and hidden elements left out. Layout tables are recognized by their `role="presentation"`, which MJML adds. The subject is a single line: line breaks become spaces. ## Locales The locales of a template are those of its subject and translations: every text needs all of them. The rendered locale is the first available among the requested locale (`fr-CA`, in any case), its language (`fr`), then the `defaultLocale` of the mailer and its language. Otherwise, rendering fails. A template without translations takes the locales of its layout. ## Sending ```ts import { createMailer } from '@dotpress/mailer' import { createSmtpProvider } from '@dotpress/mailer/smtp' const mailer = createMailer({ provider: createSmtpProvider(env.SMTP_URL), from: 'Example ', defaultLocale: 'en', }) await mailer.send(contactReceived, { to: { name: 'Ada Lovelace', address: 'ada@example.com' }, locale: 'fr-CA', data: { name: 'Ada' }, }) ``` `send()` also takes `cc`, `bcc`, `replyTo`, `from`, `subject`, `attachments` (inline ones with `contentId`), `headers`, and `tags` and `metadata` for the statistics and webhooks of the provider. Addresses, headers and attachments are checked before rendering: a line break in a name or a header throws, so user input cannot inject headers. An attachment is `{ filename, content, contentType?, contentId? }`, with `content` as bytes or as a string, sent in UTF-8. Excel and the preview of Outlook ignore the charset of a CSV file and read it as Windows-1252: start the content with a byte order mark, `'\uFEFF' + csv`, to keep its accents. `send()` returns the `messageId` given by the provider. `createMailer()` also takes a default `replyTo`, and a `logger` that logs each sent message, without the addresses. `mailer.sendMessage({ to, subject, html })` sends a message rendered elsewhere. `mailer.render(template, { locale, data })` renders without sending: previews and tests. ## Providers | Provider | Import | Use | | -------------------------- | --------------------------- | -------------------------------------------------- | | `createMemoryProvider()` | `@dotpress/mailer` | tests: keeps the messages | | `createConsoleProvider()` | `@dotpress/mailer` | development: prints the messages | | `createSmtpProvider()` | `@dotpress/mailer/smtp` | any SMTP server, through nodemailer (Node.js only) | | `createSesProvider()` | `@dotpress/mailer/aws-ses` | Amazon SES, through the AWS SDK | | `createResendProvider()` | `@dotpress/mailer/resend` | Resend | | `createSendgridProvider()` | `@dotpress/mailer/sendgrid` | SendGrid | | `createPostmarkProvider()` | `@dotpress/mailer/postmark` | Postmark | | `createBrevoProvider()` | `@dotpress/mailer/brevo` | Brevo | | `createMailjetProvider()` | `@dotpress/mailer/mailjet` | Mailjet | | `createMailgunProvider()` | `@dotpress/mailer/mailgun` | Mailgun | | `createScalewayProvider()` | `@dotpress/mailer/scaleway` | Scaleway Transactional Email | The HTTP API providers have no dependency (`fetch`). Most email services also have an SMTP interface. A provider is an object with a `name` and a `send(message)` method: write your own for another service. The settings of each provider and their limits are in the [Mailer reference](https://dotpress.dev/reference/mailer.md#providers). Switching provider changes one line: templates and calls stay the same. A message that the API of a provider cannot accept (too many recipients, an attachment type it refuses) throws before any request. :::warning Never fall back to the console provider The console provider is for development. In production, a missing provider configuration must fail at startup: falling back to the console would lose every message silently. The [Mailer example](https://dotpress.dev/examples/mailer.md) shows the pattern: ::: ```ts file="/../examples/mailer/src/mailer.ts" import { createConsoleProvider, createMailer, type MailProvider, } from '@dotpress/mailer' import { createSmtpProvider } from '@dotpress/mailer/smtp' type Env = Record /** * With `SMTP_URL`, the messages are sent over SMTP: Mailpit in development * (compose.yaml), your email service in production (most of them have an * SMTP interface). Without it, they are printed, in development only: in * production, a missing configuration must fail at startup, not lose the * messages. */ export const createProvider = ( env: Env = process.env ): MailProvider & { close?(): void } => { if (env.SMTP_URL) return createSmtpProvider(env.SMTP_URL) if (env.NODE_ENV === 'production') { throw new Error('SMTP_URL is required.') } return createConsoleProvider() } /** The mailer: `mailerPlugin` gives it the logger of each request. */ export const createAppMailer = ( provider: MailProvider, from = 'Example ' ) => createMailer({ provider, from, defaultLocale: 'en' }) ``` ### Amazon SES The function or the server needs the `ses:SendEmail` permission on the identity of the sender. When the identity has a default configuration set, or when the provider has a `configurationSetName`, the permission must also cover the configuration set, or SES answers `AccessDenied`: ```json { "Effect": "Allow", "Action": "ses:SendEmail", "Resource": [ "arn:aws:ses:::identity/example.com", "arn:aws:ses:::configuration-set/*" ] } ``` Set a custom MAIL FROM domain on the identity, such as `bounce.example.com` (one MX record and one SPF record). Without it, the envelope sender is an `amazonses.com` address: SPF does not align with the domain of the sender for DMARC, and spam filters lower the score of the messages. ## In a route ```ts import { mailerPlugin } from '@dotpress/mailer/plugin' const app = await createApp({ adapter, plugins: [mailerPlugin(mailer)] }) ``` `ctx.mailer` is the mailer, logging with the request logger. Using it without the plugin throws an explicit error. From the [Mailer example](https://dotpress.dev/examples/mailer.md): a contact form that notifies the team, and acknowledges receipt to the visitor in their language, without repeating their message (otherwise, anyone could send any text to any address through the form): ```ts handler: async ({ req, mailer }) => { const { name, email, message } = req.body const locale = negotiateLocale(req.header('accept-language'), contactReceived.locales) await mailer.send(contactNotification, { to: contactTo, replyTo: { name, address: email }, // the team answers with the Reply button data: { name, email, message, locale: locale ?? 'en' }, }) await mailer.send(contactReceived, { to: { name, address: email }, locale, data: { name } }) } ``` Sending is neither queued nor retried. For emails that must arrive despite a provider outage, send them from an [event listener](https://dotpress.dev/services/events.md): the queue retries them, and the request does not wait for the provider. The [Tasks API example](https://dotpress.dev/examples/tasks-api.md) does so. ## Testing The memory provider keeps the messages, and `expectMailSent()` of `@dotpress/testing` checks them: ```ts const outbox = createMemoryProvider() const mailer = createMailer({ provider: outbox, from: 'noreply@example.com' }) await signUp(mailer, 'ada@example.com') const mail = expectMailSent(outbox, { to: 'ada@example.com', template: welcomeMail, locale: 'en' }) expect(mail.html).toContain('https://example.com/confirm') ``` Render each locale of a template in a test, to catch a missing translation or an invalid MJML before your users do. See [Testing helpers](https://dotpress.dev/services/testing.md). ## Errors | Error | When | | ------------------ | ----------------------------------------------------------------- | | `MailDataError` | the data does not match the schema | | `MailRenderError` | invalid MJML, unknown translation key, no available locale | | `MailMessageError` | invalid address, header or attachment, or a limit of the provider | | `MailSendError` | the provider failed (`status`, `cause`) | The first render of an MJML template loads MJML (about 100 to 300 ms); later renders are cached by template and locale. See the [Mailer reference](https://dotpress.dev/reference/mailer.md) for every option. --- url: https://dotpress.dev/services/events.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Events and workers `@dotpress/events` lets your code announce what happened, and lets other code react to it, later, in workers. A route that places an order emits `order.placed` and answers at once; the confirmation email and the warehouse notification run in a worker, retried on their own when they fail. The code that emits never knows where the listeners run: in the same process during development, in a container reading Redis, or in a Lambda function reading SQS. Changing the transport changes one line. ```sh [npm] npm install @dotpress/events zod ``` ```sh [yarn] yarn add @dotpress/events zod ``` ```sh [pnpm] pnpm add @dotpress/events zod ``` ```sh [bun] bun add @dotpress/events zod ``` ```sh [deno] deno add npm:@dotpress/events npm:zod ``` ## Concepts | | Role | Where | | ------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------ | | **Event** (`defineEvent`) | a fact, with a name and the schema of its payload | shared code | | **Listener** (`defineListener`) | a reaction to an event, with a unique name | shared code | | **Bus** (`createEventBus`) | validates the events emitted, sends one message per listener to its transport | the code that emits: API, scripts | | **Transport** | sends the messages to a queue: memory, Redis, SQS, Postgres… | the configuration of the bus | | **Worker** (`createWorker`) | runs the listeners of the messages it receives | a container, a Lambda function, `dotpress-events work` | `emit()` sends **one message per listener**: each listener is retried on its own, and can even run on another platform. ## Events and listeners From the [Events example](https://dotpress.dev/examples/events.md): ```ts file="/../examples/events/src/events.ts" import { defineEvent, defineListener } from '@dotpress/events' import { z } from 'zod' // Shared by the API, which emits, and by the worker, which runs the // listeners. /** A fact: an order was placed. Payloads travel as JSON. */ export const orderPlaced = defineEvent({ name: 'order.placed', schema: z.object({ orderId: z.uuid(), items: z.array(z.object({ sku: z.string(), quantity: z.number().int() })), }), }) // Each listener gets its own message: it is retried on its own. `load` // keeps the code of the listeners out of the API, which only needs their // names. export const sendOrderConfirmation = defineListener(orderPlaced, { name: 'send-order-confirmation', load: () => import('./listeners/send-order-confirmation.ts'), }) export const notifyWarehouse = defineListener(orderPlaced, { name: 'notify-warehouse', load: () => import('./listeners/notify-warehouse.ts'), }) export const listeners = [sendOrderConfirmation, notifyWarehouse] ``` `load` imports the code of a listener, the default export of its module, only in the worker: the API that emits only needs the names of the listeners, not their dependencies. Event names use letters, digits, `.`, `_`, `:` and `-`; a listener name is unique, and renaming it orphans the messages still in queues under the old name. A listener can also be written inline, with `handle`: ```ts import { defineEvent, defineListener } from '@dotpress/events' import { z } from 'zod' declare const crm: { addContact(userId: string): Promise } const userCreated = defineEvent({ name: 'user.created', schema: z.object({ userId: z.string() }), }) const syncCrm = defineListener(userCreated, { name: 'sync-crm', handle: async ({ payload, logger }) => { await crm.addContact(payload.userId) logger.info({ userId: payload.userId }, 'Contact added to the CRM') }, }) ``` The listener receives the parsed `payload`, typed by the schema, and: | Field | Content | | ------------------------- | ------------------------------------------------------------- | | `id` | the identifier of the message, the same for every attempt | | `attempt` | the attempt number, from 1 | | `emissionId`, `emittedAt` | the emission | | `metadata` | the metadata of the emission: the `requestId` with the plugin | | `logger` | the logger of the worker | | `event`, `listener` | the names | ### Payloads **Payloads travel as JSON.** The bus serializes the payload, then validates it with the schema: an invalid payload throws an `EventPayloadError` at `emit()`, not later in a worker. Dates travel as ISO strings: convert them in the schema (`z.coerce.date()`, `.transform()`) if listeners need `Date` objects. Workers validate the payload again, against the current schema: a message emitted by a previous version of your code is checked too. :::warning Pass identifiers, not secrets Messages are stored by queues, shown in their consoles and kept in dead-letter queues. Send `{ userId }`, never a password, a token or personal data the listener can load itself. ::: ### Retries and idempotency **A listener throws to be retried.** The transport delivers the message again, then moves it to its dead-letter queue after its retry limit. **Make listeners idempotent.** Queues deliver messages at least once: a message can run twice, after a timeout or a duplicate delivery. Use `id` to ignore duplicates (a unique constraint, an idempotency key sent to the API you call), or make running twice harmless. Some queues also ignore a message sent twice, by its `id` ([see each queue](https://dotpress.dev/deployment/event-workers.md)), but not all of them, and not always: it is a bonus, not a guarantee. ```ts file="/../examples/events/src/listeners/notify-warehouse.ts" import type { EventPayload, ListenerContext } from '@dotpress/events' import type { orderPlaced } from '../events.ts' /** * Sends the order to the warehouse service (`WAREHOUSE_URL`). When the * service fails, the listener throws: the message is retried, then kept in * the failed jobs of the queue. */ export default async ({ payload, id, logger, }: ListenerContext>) => { const url = process.env.WAREHOUSE_URL if (!url) { logger.info( { orderId: payload.orderId }, 'WAREHOUSE_URL is not set: the warehouse is not notified' ) return } const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', // A message can be delivered twice (retry after a timeout): the id // is the same for every attempt, so the service ignores duplicates. 'idempotency-key': id, }, body: JSON.stringify(payload), signal: AbortSignal.timeout(10_000), }) if (!res.ok) throw new Error(`The warehouse answered ${res.status}`) logger.info({ orderId: payload.orderId }, 'Warehouse notified') } ``` ## Emitting ```ts import { createEventBus, createMemoryTransport, defineEvent } from '@dotpress/events' import { z } from 'zod' const invoicePaid = defineEvent({ name: 'invoice.paid', schema: z.object({ invoiceId: z.string(), paidAt: z.iso.datetime() }), }) const events = createEventBus({ transport: createMemoryTransport(), listeners: [] }) await events.emit( invoicePaid, { invoiceId: 'F-1', paidAt: new Date().toISOString() }, { delay: '1h', metadata: { source: 'payments' } } // optional ) ``` The payload is typed by the schema of the event. `delay`, a number of seconds or a [duration](https://dotpress.dev/concepts/options.md#durations) like `'1h'`, postpones the listeners, within the limit of the transport. `emit()` returns the `emissionId`, and one `{ id, listener, transport }` per listener; an event without listeners is not sent. :::warning Emit after the transaction commits An event describes something that happened. Emitted inside a database transaction that rolls back, it describes something that did not. Commit first, then emit. ::: ### Send failures When some messages cannot be sent (the queue is down), `emit()` throws an `EventEmitError`, which lists the `sent` and `failed` messages. `retry()` sends the failed messages again, with the same ids, delay and metadata; the sent ones are not sent again: ```ts import { createEventBus, createMemoryTransport, defineEvent, EventEmitError } from '@dotpress/events' import { z } from 'zod' const invoicePaid = defineEvent({ name: 'invoice.paid', schema: z.object({ invoiceId: z.string(), paidAt: z.iso.datetime() }), }) const events = createEventBus({ transport: createMemoryTransport(), listeners: [] }) const payload = { invoiceId: 'F-1', paidAt: new Date().toISOString() } try { await events.emit(invoicePaid, payload) } catch (error) { if (error instanceof EventEmitError) await error.retry() else throw error } ``` A new failure throws a new `EventEmitError`, whose `sent` also lists the messages sent before, with its own `retry()`. The error does not expose the payload: it can be logged as is. A queue that cannot be reached does not always fail at once: a client may wait for the connection to come back. `emit()` waits 10 seconds at most for each transport (`sendTimeout` of `createEventBus()`, `false` for no limit); the messages of a transport that did not answer fail with an `EventSendTimeoutError`. A send given up this way may still complete later: `retry()` sends the same message ids, and listeners ignore duplicates by `id`. ### Emitting again: `emissionId` `retry()` only works in the process that emitted. Each call to `emit()` is a new emission, with new message ids: emitting again later (a job that replays an outbox, a webhook received twice) runs again the listeners whose message was already sent. To avoid that, pass an `emissionId`, the idempotency key of the emission. The message ids derive from it: the same `emissionId` gives the same ids, and listeners ignore the duplicates by `id`. ```ts import { createEventBus, createMemoryTransport, defineEvent } from '@dotpress/events' import { z } from 'zod' const invoicePaid = defineEvent({ name: 'invoice.paid', schema: z.object({ invoiceId: z.string(), paidAt: z.iso.datetime() }), }) const events = createEventBus({ transport: createMemoryTransport(), listeners: [] }) const invoice = { id: 'F-1', paidAt: new Date().toISOString() } await events.emit( invoicePaid, { invoiceId: invoice.id, paidAt: invoice.paidAt }, { emissionId: `invoice-paid:${invoice.id}` } ) ``` **The `emissionId` names one occurrence of the fact, not its entity.** An invoice is paid once: `invoice-paid:${invoice.id}` fits. An order is updated many times: `order-updated:${order.id}` would make every update a duplicate of the first one; use `${order.id}:${order.version}`, or the id of an outbox row. It has 1 to 200 characters, without control characters. Only the ids are stable: `emittedAt` is the date of each call. Without `emissionId`, make listeners idempotent on the data they change (a unique constraint on the order, an idempotency key derived from it), not only on the message `id`. ## In a route ```ts import { eventsPlugin } from '@dotpress/events/plugin' const app = await createApp({ adapter, plugins: [eventsPlugin(events)] }) defineRoute({ method: 'post', path: '/orders', handler: async ({ req, events }) => { const order = await orders.place(req.body) await events.emit(orderPlaced, { orderId: order.id, items: order.items }) return order }, }) ``` `ctx.events` logs with the request logger, and adds the `requestId` to the metadata of the events: the logs of the listeners link back to the request. Using `ctx.events` without the plugin throws an explicit error. Outside a route, `events.withContext({ logger, metadata })` does the same. ## Transports | Transport | Import | Use | | ---------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------- | | `createSyncTransport()` | `@dotpress/events` | runs the listeners inside `emit()`. Development, tests, apps without a queue | | `createMemoryTransport()` | `@dotpress/events` | an in-process queue with retries. Development and tests: messages are lost when the process stops | | `createBullmqTransport()` | `@dotpress/events/bullmq` | Redis, through BullMQ | | `createSqsTransport()` | `@dotpress/events/aws-sqs` | Amazon SQS, with Lambda workers | | `createPgBossTransport()` | `@dotpress/events/pg-boss` | Postgres, through pg-boss: no other infrastructure than your database | | `createCloudflareQueueTransport()` | `@dotpress/events/cloudflare-queues` | Cloudflare Queues | | `createPubSubTransport()` | `@dotpress/events/google-pubsub` | Google Cloud Pub/Sub | | `createServiceBusTransport()` | `@dotpress/events/azure-service-bus` | Azure Service Bus | The example picks its transport from the configuration: BullMQ with Redis, an in-memory queue in the API process without it. ```ts file="/../examples/events/src/bus.ts" import { createEventBus, createMemoryTransport, type EventBusOptions, type Transport, } from '@dotpress/events' import { createBullmqTransport } from '@dotpress/events/bullmq' import { listeners } from './events.ts' type Env = Record /** Name of the BullMQ queue, shared by the API and the worker. */ export const queueName = (env: Env = process.env) => env.EVENTS_QUEUE ?? 'events' /** BullMQ connection options from a Redis URL (`redis://` or `rediss://`). */ export const redisConnection = (redisUrl: string) => { const url = new URL(redisUrl) return { host: url.hostname, port: Number(url.port || 6379), ...(url.username && { username: decodeURIComponent(url.username) }), ...(url.password && { password: decodeURIComponent(url.password) }), ...(url.pathname.length > 1 && { db: Number(url.pathname.slice(1)) }), ...(url.protocol === 'rediss:' && { tls: {} }), } } /** A transport, and how to close it on shutdown. */ export type ClosableTransport = Transport & { close(): Promise } /** * With `REDIS_URL`, the events go to a BullMQ queue, handled by the worker * (`npm run worker`). Without it, an in-memory queue runs the listeners in * this process: development without Redis. */ export const createTransport = (env: Env = process.env): ClosableTransport => { if (env.REDIS_URL) { return createBullmqTransport({ queue: queueName(env), // While Redis is unreachable, emit() fails at once. connection: { ...redisConnection(env.REDIS_URL), enableOfflineQueue: false, }, }) } const memory = createMemoryTransport() // Waits for the listeners in progress. return Object.assign(memory, { close: () => memory.drain() }) } /** The event bus of the API. */ export const createBus = ( transport: Transport, options: Pick = {} ) => createEventBus({ transport, listeners, ...options }) ``` Several transports can be used together: name them in the bus with `transports: { default, … }`, and route an event, or a single listener, with its `transport` option. Declare the names in the `EventTransports` interface to type-check them; the bus checks at startup that every listener has its transport. The setup of each platform (queues, dead letters, Lambda, containers) is described in [Event workers](https://dotpress.dev/deployment/event-workers.md). ## Workers A worker runs the listeners of the messages it receives. During development, run it next to your API with `dotpress-events work`: ```sh npx dotpress-events work src/worker.ts --watch ``` The module exports the `worker`, the `source` of the messages, and optionally a `logger`: ```ts file="/../examples/events/src/worker.ts" import { createConsoleLogger } from '@dotpress/core' import { createWorker } from '@dotpress/events' import { createBullmqSource } from '@dotpress/events/bullmq' import { queueName, redisConnection } from './bus.ts' import { listeners } from './events.ts' // Entry of `dotpress-events work src/worker.ts`: reads the BullMQ queue and // runs the listeners, until Ctrl+C or SIGTERM (it then finishes the jobs in // progress). In production, run it in its own container. const redisUrl = process.env.REDIS_URL if (!redisUrl) { throw new Error( 'REDIS_URL is required: without it, the API runs the listeners itself.' ) } export const logger = createConsoleLogger({ bindings: { process: 'worker' } }) export default { worker: createWorker({ listeners, logger, // The attempts of the BullMQ jobs (3 by default): the last failure is // reported as final, for alerts. maxAttempts: 3, onFailure: (error, { envelope, attempt, final }) => { if (final) { logger.error( { error, listener: envelope?.listener, id: envelope?.id, attempt }, 'Event listener gave up: the job stays in the failed jobs' ) } }, }), source: createBullmqSource({ queue: queueName(), connection: redisConnection(redisUrl), concurrency: 5, }), logger, } ``` Ctrl+C or `SIGTERM` stops the worker after the messages in progress; a second signal, a second later or more, exits at once. In production, the same command is the entry point of a container; on AWS Lambda, the SQS handler replaces it. See [Event workers](https://dotpress.dev/deployment/event-workers.md). ## Failures | Failure | What happens | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | The listener throws | the message is retried, then moved to the dead-letter queue after the retry limit | | Invalid payload, unknown listener | retrying would not help: the message goes to the dead-letter queue at once when the transport can, or fails until the retry limit | `onFailure(error, { envelope, attempt, final, reason })`, an option of the worker, is called for every failure: use it for alerts. Set `maxAttempts` to the retry limit of the queue, so that the last attempt is reported as `final`. An `unknown-listener` failure usually means a deployment mistake: a listener routed to a queue whose workers do not run it. The options, the failure reasons, the logs and the errors are listed in the [Events reference](https://dotpress.dev/reference/events.md). ## Testing The memory transport runs the listeners in the test, and `drain()` waits for them: ```ts const transport = createMemoryTransport({ retryDelay: () => 0 }) const events = createEventBus({ transport, listeners }) await placeOrder(events, order) await transport.drain() expect(transport.sent).toMatchObject([{ event: 'order.placed', listener: 'notify-warehouse' }]) ``` To test the code that emits without running the listeners, use `createFakeEventBus()` and `expectEventEmitted()` of `@dotpress/testing`: ```ts const events = createFakeEventBus() await placeOrder(events, order) expectEventEmitted(events, orderPlaced, { orderId: order.id }) ``` See [Testing helpers](https://dotpress.dev/services/testing.md). --- url: https://dotpress.dev/services/cache.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Cache and memoization `@dotpress/cache` provides two tools, for two different problems: | | Memo | Cache | | --------------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | **Avoids** | loading the same value several times **within one request** | loading the same value **on every request** | | **Lives** | as long as the request (or the event message, the job) | minutes, hours, days | | **Stored in** | the memory of the request | a store: memory, Redis, Upstash, Workers KV | | **Freshness** | always fresh: each request starts with an empty memo | can be outdated: expires with a `ttl`, or when you invalidate it | | **Typical use** | the current user, loaded by a middleware and a handler; the authors of a list of articles | a catalog, a price list, a dashboard, the response of a slow service | Start with the memo: it saves queries without any risk of serving outdated data. Add the cache for values that are expensive to load and change rarely. ```sh [npm] npm install @dotpress/cache ``` ```sh [yarn] yarn add @dotpress/cache ``` ```sh [pnpm] pnpm add @dotpress/cache ``` ```sh [bun] bun add @dotpress/cache ``` ```sh [deno] deno add npm:@dotpress/cache ``` ## Set up The plugin gives each request a memo, `ctx.memo`, and the cache, `ctx.cache`: ```ts import { createCache, createMemoryStore } from '@dotpress/cache' import { cachePlugin } from '@dotpress/cache/plugin' const cache = createCache({ store: createMemoryStore(), prefix: 'app' }) const app = await createApp({ adapter, plugins: [cachePlugin({ cache })] }) ``` `cachePlugin()` without `cache` provides the memo only. ## Memo ### Load a value once per request The authentication middleware loads the account of the user, and the handler needs it too. Declare how to load it, then ask the memo: ```ts import { defineMiddleware, defineRoute, forbiddenError } from '@dotpress/core' import { defineMemo } from '@dotpress/cache' import '@dotpress/cache/plugin' interface Account { id: string plan: 'free' | 'pro' suspended: boolean } declare const db: { accounts: { findById(id: string): Promise } } // How to load an account: declared once, in a module. export const loadAccount = defineMemo({ name: 'account', load: (id: string) => db.accounts.findById(id), }) const requireActiveAccount = defineMiddleware(async (ctx) => { const account = await ctx.memo(loadAccount, ctx.req.params.accountId) // loads it if (!account || account.suspended) return forbiddenError() }) defineRoute({ path: '/accounts/:accountId/billing', middlewares: [requireActiveAccount], handler: async ({ req, memo }) => { const account = await memo(loadAccount, req.params.accountId) // no query: memoized return { plan: account?.plan } }, }) ``` For `GET /accounts/42/billing`, the middleware and the handler both ask the memo for account `42`: the database is queried once. They stay independent: neither has to pass the account to the other. - **Single flight**: calls made while the value loads wait for the same load. - **Failures are not kept**: a failed load fails the calls in progress, and the next call loads again. - **Keys**: the arguments of `load`, compared by value; a `key` option handles other arguments (`key: (user) => user.id`). - **Values are not copies**: a caller that mutates one changes it for the others. - After an update, `ctx.memo.set(loadAccount, id, account)` replaces the value, and `ctx.memo.delete(loadAccount, id)` loads it again next time; `memo.clear()` forgets everything. ### Batch the loads A list of 50 articles shows the author of each. Loading the authors one by one makes 50 queries: the N+1 problem. With `batch` instead of `load`, the memo collects the keys requested in the same tick, and loads them in **one** call: ```ts import { defineRoute } from '@dotpress/core' import { defineMemo } from '@dotpress/cache' import '@dotpress/cache/plugin' interface User { id: string name: string } declare const db: { users: { findManyById(ids: readonly string[]): Promise } articles: { list(): Promise<{ id: string; title: string; authorId: string }[]> } } export const loadAuthor = defineMemo({ name: 'author', // Receives every id requested in the same tick, without duplicates. batch: async (ids: readonly string[]) => { const users = await db.users.findManyById(ids) // WHERE id IN (…) return new Map(users.map((user) => [user.id, user])) // unknown ids give undefined }, }) defineRoute({ path: '/articles', handler: async ({ memo }) => { const articles = await db.articles.list() // 50 calls to the memo, one query to the database return Promise.all( articles.map(async (article) => ({ ...article, author: await memo(loadAuthor, article.authorId), })) ) }, }) ``` The code that renders one article does not change: it asks for one author, and the memo groups the requests. `batch` returns a `Map` by key, or an array in the order of the keys, where an `Error` fails its key only. `maxBatchSize` limits the keys per call. ### One memo per unit of work A memo lives as long as its request: each request starts empty, so it never serves outdated data. For the same reason, never keep a memo for the whole process: it would grow forever, and serve old values. In an event listener or a job, create one per message with `createMemo()` (see [Outside a route](#outside-a-route)). ## Cache ### Keep a value across requests The plans of a billing service change a few times a year, and the service takes 300 ms to answer. Declare a cache entry, and read through it: ```ts import { defineRoute } from '@dotpress/core' import { defineCacheEntry } from '@dotpress/cache' import { z } from 'zod' import '@dotpress/cache/plugin' declare const billing: { getPlan(id: string): Promise<{ id: string; name: string; price: number }> } export const planCache = defineCacheEntry({ name: 'plan', key: (id: string) => id, schema: z.object({ id: z.string(), name: z.string(), price: z.number() }), ttl: '1h', }) defineRoute({ path: '/plans/:id', handler: ({ req, cache }) => // From the cache, or from the service on a miss, then cached for an hour cache.getOrSet(planCache, req.params.id, () => billing.getPlan(req.params.id)), }) ``` - **`getOrSet`** returns the cached value, or calls the loader and caches its result. Concurrent requests for a missing value share one load. A failed load, or a load returning `undefined` (not found), is not cached. - **`get`**, **`set`** and **`delete`** are the usual operations. - **Durations** are seconds, or strings: `'500ms'`, `'30s'`, `'10m'`, `'1h'`, `'7d'` (see [Durations](https://dotpress.dev/concepts/options.md#durations)). The `ttl` of an entry overrides the `ttl` of the cache, 1 hour by default. - **The `schema`** types the value, and checks it when read: a value written by an older version of the app that no longer matches is a miss, not a crash. Values are stored as JSON: use `z.coerce.date()` for dates. - **Keys** are `prefix:name:v1:key`; longer keys than the store accepts are hashed. Increase the `version` of an entry when the shape of its values changes: the old values are ignored. - **Values** are serialized as JSON (or with a `serializer`, such as superjson). `null` is cached; `undefined` is not. ### Expire values when the data changes A cached value is outdated as soon as the data changes. Delete it after an update: ```ts await db.plans.update(id, changes) await cache.delete(planCache, id) ``` When one change affects many values, tag them, and invalidate the tag: ```ts export const productCache = defineCacheEntry({ name: 'product', key: (id: string) => id, tags: (id: string) => [`product:${id}`, 'catalog'], }) await cache.invalidateTags(['catalog']) // after an import: every product expires ``` Tags are computed from the arguments of the entry, not from the value: a value expires without being read. Reading a value with tags costs one more round trip to the store, for their tokens: see [Tags](https://dotpress.dev/reference/cache.md#tags). ### Serve outdated values when the source fails Some data is better a little outdated than missing. An entry decides how expired values are served: ```ts export const catalogCache = defineCacheEntry({ name: 'catalog', ttl: '5m', grace: '1d', // when the loader fails, serve the expired value, for one more day staleWhileRevalidate: '1m', // serve the expired value at once, and refresh it in the background timeout: '300ms', // a slow loader serves the expired value, and goes on in the background }) ``` | Option | Effect, once the `ttl` is over | | ---------------------- | --------------------------------------------------------------------------------------- | | `grace` | When the loader fails or times out, the expired value is served instead of the error. | | `graceBackoff` | After such a failure, the loader is not called again for this delay (`10s` by default). | | `staleWhileRevalidate` | The expired value is served at once, and reloaded in the background. | | `timeout` | A load slower than this serves the expired value of the grace period. | | `hardTimeout` | A load slower than this fails, or serves the expired value. | | `lock` | One instance loads a missing value, the others wait for it (Redis). | ### When the store fails The cache is an optimization: by default, it **fails open**. When the store is down, a read becomes a miss (the loader runs), a write is skipped, and the app keeps working. Every failure is logged, and passed to `onError`: ```ts const cache = createCache({ store, prefix: 'app', storeTimeout: '200ms', // a slower store counts as a failure onError: (error, { operation }) => metrics.increment('cache.store_error', { operation }), }) ``` Set `storeTimeout`: while a Redis client reconnects, its commands wait, and the requests would wait with them. `failOpen: false` throws a `CacheStoreError` instead. `onAccess` receives each hit, miss and stale value, for metrics. ### Stores | Store | Import | Use | | ------------------------------ | ------------------------------- | ---------------------------------------------------------------------------------- | | `createMemoryStore()` | `@dotpress/cache` | one instance, development, tests; 10,000 entries at most by default (`maxEntries`) | | `createRedisStore({ client })` | `@dotpress/cache/redis` | Redis or Valkey, with a node-redis or ioredis client | | `createUpstashStore()` | `@dotpress/cache/upstash` | Upstash Redis, over HTTP | | `createCloudflareKvStore()` | `@dotpress/cache/cloudflare-kv` | Cloudflare Workers KV | With several instances of the API, use a shared store: with the memory store, each instance has its own cache, and an invalidation only reaches one of them. The settings and limits of each store, Upstash and Workers KV included, are in the [Cache reference](https://dotpress.dev/reference/cache.md#stores). ```ts import { createClient } from 'redis' import { createRedisStore } from '@dotpress/cache/redis' const client = createClient({ url: env.REDIS_URL }) client.on('error', (error) => logger.error({ error }, 'Redis error')) await client.connect() const cache = createCache({ store: createRedisStore({ client }), prefix: 'app', storeTimeout: '200ms' }) // On shutdown: await client.close() (node-redis 5 or later; quit() with node-redis 4 and ioredis) ``` ## Using both The two tools combine: the cache keeps the result across requests, and the memo avoids repeated queries while computing it on a miss. In the [Cache example](https://dotpress.dev/examples/cache.md) (simplified here), the list of articles is cached for a minute; when it is computed, the authors are loaded with one batched query: ```ts handler: ({ cache, memo }) => cache.getOrSet(articleListCache, async () => { const articles = await db.articles.list() // On a miss only: one query for every author, through the memo return Promise.all(articles.map((article) => toView(memo, loadAuthor, article))) }) ``` The example counts the queries of its fake database: its tests show what each tool saves. ## Outside a route Both tools work without an app, in a worker or a script: ```ts import { createCache, createMemo } from '@dotpress/cache' const memo = createMemo() // one per message or job const account = await memo(loadAccount, id) const cache = createCache({ store, prefix: 'app' }) const plan = await cache.getOrSet(planCache, planId, () => billing.getPlan(planId)) ``` ### Memo without passing the context Services deep in the code do not always receive `ctx`. With `memoScope: asyncLocalMemo`, each request runs in the scope of its memo (`AsyncLocalStorage`), and a memoized loader works anywhere during the request: ```ts import { asyncLocalMemo, memoized } from '@dotpress/cache/als' const app = await createApp({ adapter, plugins: [cachePlugin({ cache, memoScope: asyncLocalMemo })] }) export const getAccount = memoized(loadAccount) // in any service called during the request: const account = await getAccount(id) ``` In an event listener or a job, open a scope with `runWithMemo(() => …)`: one memo per message. `AsyncLocalStorage` works on Node.js, Bun, Deno, and Cloudflare Workers with `nodejs_compat`. Outside a scope, a memoized loader throws: there is no global memo. --- url: https://dotpress.dev/services/testing.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Testing helpers `@dotpress/testing` runs your app in memory, and checks what it does besides answering: the events it emits, the emails it sends, its Lambda handler. For the basics (the memory adapter, `createTestApp()`), see [Testing](https://dotpress.dev/routing/testing.md). ```sh npm install -D @dotpress/testing vitest ``` ## Events `expectEventEmitted()` checks that an event was emitted, and returns the last matching emission. The source is a fake event bus, which checks the emissions like a real bus without running the listeners, or a memory transport, which runs them: ```ts import { createFakeEventBus } from '@dotpress/events' import { expectEventEmitted, expectEventNotEmitted } from '@dotpress/testing' const events = createFakeEventBus() await signUp(events, 'ada@example.com') expectEventEmitted(events, userCreated, { email: 'ada@example.com' }) expectEventEmitted(events, 'user.created', undefined, { times: 1, metadata: { requestId: 'req-1' } }) expectEventNotEmitted(events, userDeleted) ``` - `event`: the definition, or its name. - `payload`: objects are matched partially (like `toMatchObject()`), other values exactly; asymmetric matchers work (`expect.any(String)`). - `options`: `times` (an exact number; at least one by default), `metadata` (matched partially), `delay`. With the plugin, give the fake bus to `eventsPlugin()`: `ctx.events` records into it, with the `requestId` in the metadata. ## Emails `expectMailSent()` checks the messages kept by the memory provider of the mailer (`outbox.sent`, `last()`, `clear()`), and returns the last matching one. `renderMail(template, { locale, defaultLocale, data })` renders a template without a mailer, to test each locale: ```ts import { createMailer, createMemoryProvider } from '@dotpress/mailer' import { expectMailSent, expectNoMailSent } from '@dotpress/testing' const outbox = createMemoryProvider() const mailer = createMailer({ provider: outbox, from: 'noreply@example.com' }) await signUp(mailer, 'ada@example.com') const mail = expectMailSent(outbox, { to: 'ada@example.com', template: welcomeMail, locale: 'en' }) expect(mail.html).toContain('https://example.com/confirm') expectNoMailSent(outbox, { to: 'grace@example.com' }) ``` - `to`, `cc`, `bcc`, `replyTo`: an address or a list, all among the recipients. `from`: the sender. - `template`: the template, or its name. - `subject`, `html`, `text`, `locale`, `tags`, `metadata`, `headers`, `attachments`: matched like `toMatchObject()`, with asymmetric matchers. - `options.times`: an exact number of messages. A failed assertion throws an `ExpectationError` listing what was emitted or sent: the failure explains itself. ## Logs `createMemoryLogger()` records the log lines instead of printing them: the tests stay quiet, and can check what was logged. ```ts const logger = createMemoryLogger() await createApp({ adapter, logger }) expect(logger.entries).toContainEqual({ level: 'error', args: [expect.any(Error), 'Unhandled error while processing request'], }) ``` ## AWS Lambda `createLambdaTarget(handler, { format, close? })` sends requests to a Lambda handler as simulated events, and converts the results back: test the handler without an AWS account. `format` is `'v1'` (API Gateway REST API), `'v2'` (HTTP API, Function URLs), `'alb'` (Application Load Balancer with multi-value headers) or `'alb-single-value'` (without them, the default of a target group: one value per header and query key, and the response headers read from `headers` only). A failed invocation gets a `502`, like API Gateway. To run the conformance suite on a Lambda handler, pass `bufferedResponses: true`: the scenarios that need incremental streaming or client disconnections are skipped. `toLambdaEvent()` and `fromLambdaResult()` are exported for finer tests. The [Fastify](https://dotpress.dev/examples/fastify.md) and [Hono](https://dotpress.dev/examples/hono.md) examples test their handler, and their bundle, this way. ## Writing an adapter Every adapter of Dotpress passes the conformance suite, `runConformanceSuite()`: routing, parsing, validation, errors, middlewares and responses, streams and Server-Sent Events included. An adapter for another server runs it too: ```ts import { createApp } from '@dotpress/core' import { createHttpTarget, runConformanceSuite } from '@dotpress/testing/conformance' import { myAdapter } from '../src/index.ts' runConformanceSuite({ name: 'my-adapter', async setup(options) { const adapter = myAdapter() const app = await createApp({ ...options, adapter }) const { port } = await app.listen(0, '127.0.0.1') return createHttpTarget(`http://127.0.0.1:${port}`, { close: () => app.close() }) }, }) ``` The suite has its own entry, `@dotpress/testing/conformance`. A target sends the requests of the suite (`fetch(path, init)`) and stops the app (`close()`, the option of the same name, which does nothing by default). An adapter that does not listen on a port returns `createFetchTarget(handle, { close })`, where `handle` takes a Web `Request` and returns a `Response`. Every helper and option: see the [Testing reference](https://dotpress.dev/reference/testing.md). --- url: https://dotpress.dev/reference/application.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Application `createApp()` and the object it returns. For an introduction, see [How it works](https://dotpress.dev/concepts/how-it-works.md#the-app). ## createApp() ```ts import { createApp } from '@dotpress/core' function createApp(options: AppOptions): Promise ``` `createApp()` sets up the plugins, compiles the routes, runs the `onInit` hooks, mounts the routes on the adapter, then runs the `onReady` hooks. It does not start a server: call `app.listen()`, or hand the app to a serverless handler. ### Options Unknown options are rejected, like those of every Dotpress function: see [Options and durations](https://dotpress.dev/concepts/options.md). | Option | Type | Default | Description | | ------------------- | ----------------------------------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `adapter` | `HttpAdapter` | required | The HTTP adapter: [Express, Fastify, Hono, AWS Lambda](https://dotpress.dev/adapters/index.md). | | `routers` | `Router[]` | `[globalRouter]` | The routers to mount. Without it, the routes declared with `defineRoute()`. See [Routers](https://dotpress.dev/routing/routes.md#routers). | | `plugins` | `Plugin[]` | `[]` | Set up in the given order, dependencies first. See [Plugin API](https://dotpress.dev/reference/plugins.md). | | `middlewares` | `Middleware[]` | `[]` | Run on every route, after the plugin middlewares, before the group and route middlewares. | | `responseFilters` | `ResponseFilter[]` | `[]` | Applied to every successful JSON result, before the plugin and router filters. | | `basePath` | `string` | — | Prefix of every route, plugin routes included, when the proxy forwards the full path. | | `publicBasePath` | `string` | — | Prefix removed by the proxy: routes are not prefixed, but `publicPath()` is. Cannot be combined with `basePath`. | | `cors` | `CorsOptions` | disabled | Answers cross-origin requests. See [CORS options](#cors-options). | | `logger` | `Logger` | console logger | Any logger with the [`Logger`](#logger) interface, Pino included. | | `exposeErrors` | `boolean` | `false` | Adds the name, message and stack of unexpected errors to `500` responses. Never in production. | | `generateRequestId` | `(req: DotpressRequest) => string` | `crypto.randomUUID()` | The ID of each request, sent as `X-Request-ID`: `(req) => req.header('x-request-id') ?? crypto.randomUUID()` keeps the one of a proxy. | | `onError` | `(error: unknown, ctx: RequestContext \| undefined) => void \| Promise` | — | Called with every unexpected error (anything but an `HttpError`). `ctx` is undefined outside a route. | The body size limit is an option of the adapter (`bodyLimit`, 1 MiB by default), or of a route. See [Common options](https://dotpress.dev/adapters/index.md#common-options). ### Startup errors `createApp()` rejects, instead of starting with a wrong configuration, when: - `adapter` is missing; - `basePath` and `publicBasePath` are both set, or one is not a valid path; - two routes have the same method and path (`Route conflict: "GET /articles/:id" is already defined…`); - a plugin is installed twice, depends on a plugin that is not installed, or the dependencies are circular; - two plugins provide the same context key; - the `cors` option is invalid, for instance `origin: '*'` with `credentials: true`; - a `setup()`, `onInit` or `onReady` hook throws. Route definitions are checked when they are declared: a path with unsupported syntax, an unknown method or an invalid `status` throws at `defineRoute()`. ## App | Member | Description | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `listen(port, host?)` | Starts the server, and returns `{ port, host }`: the actual port with `listen(0)`. Not available on serverless adapters. | | `close()` | Stops the server, waits for the pending requests and closes the streamed responses, then runs the `onClose` hooks of the plugins, last plugin first. Rejects with the first failing hook, after running them all. | | `routes` | The mounted routes (`RouteInfo[]`), with the base path: method, path, path parameters, schemas, metadata, security, status. | | `plugins` | The installed plugins, in setup order. | | `basePath`, `publicBasePath` | The normalized options, or `''`. | | `publicPath(path)` | The path seen by the browser: `app.publicPath('/login')` gives `'/my-app/api/login'` with a base path. | | `logger` | The logger of the app. | | `adapter` | The adapter given to `createApp()`. | | `native()` | The native application of the adapter: Express app, Fastify instance, Hono app. | ```ts const app = await createApp({ adapter: expressAdapter(), routers, plugins }) await app.listen(3000) process.once('SIGTERM', () => void app.close()) ``` ## CORS options ```ts cors: { origin: ['https://app.example.com', /\.example\.com$/], credentials: true, exposedHeaders: ['X-Request-ID'], maxAge: 600, } ``` | Option | Type | Default | Description | | ---------------- | ---------- | --------------------- | ----------------------------------------------------------------------------------- | | `origin` | see below | required | The allowed origins. | | `credentials` | `boolean` | `false` | Allows cookies and `fetch()` with `credentials: 'include'`. Not with `origin: '*'`. | | `allowedHeaders` | `string[]` | the requested headers | Request headers allowed by preflight responses. | | `exposedHeaders` | `string[]` | none | Response headers readable by the browser, besides the safelisted ones. | | `maxAge` | `number` | — | How long browsers cache preflight responses, in seconds. | `origin` accepts `'*'` (any origin, without credentials), an origin (`'https://app.example.com'`), a regular expression, a list of origins and regular expressions, or a function `(origin, req) => boolean | Promise`, where `req` is the request (`req.header()`, `req.path`…). See [CORS](https://dotpress.dev/routing/http-options.md#cors) for preflight requests and error responses. ## Logger ```ts interface Logger { debug: LogFn info: LogFn warn: LogFn error: LogFn child(bindings: Record): Logger } interface LogFn { (message: string, ...args: unknown[]): void (data: object, message?: string, ...args: unknown[]): void } ``` The signature is the one of Pino: `logger: pino()` works as is. The default logger writes to the `console`: ```ts import { createConsoleLogger } from '@dotpress/core' const logger = createConsoleLogger({ level: 'debug', bindings: { service: 'api' } }) ``` | Option | Default | Description | | ---------- | -------- | ----------------------------------- | | `level` | `'info'` | `debug`, `info`, `warn` or `error`. | | `bindings` | `{}` | Fields added to every entry. | See [Logging](https://dotpress.dev/routing/logging.md). ## For adapter authors An adapter implements the `HttpAdapter` contract of `@dotpress/core`, with the `NormalizedRequest` and `NormalizedResponse` types. The rest of what it needs comes from `@dotpress/core/adapter`, which applications do not need: ```ts import { createRouteMatcher, parseQueryString, parseRequestBody, type CompiledRoute, type DotpressRuntime, } from '@dotpress/core/adapter' ``` | Export | Description | | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `CompiledRoute`, `DotpressRuntime` | The routes to mount, and the responses for requests that match none. | | `createRouteMatcher()` | Matches a request to a route, with the rules of every adapter. | | `parseQueryString()`, `parseRequestBody()`, `DEFAULT_BODY_LIMIT` | The query and the body, limited to 1 MiB by default. | | `malformedBodyError()`, `payloadTooLargeError()`, `unsupportedMediaTypeError()` | The errors of an unreadable body. | | `fromWebRequest()`, `readRequestBody()`, `toWebResponse()` | For adapters built on the Web `Request` and `Response`. | | `registerLazyApp(factory)` | For a handler that creates the app at the first request (AWS Lambda): when `dotpress-openapi` documents the app, the factory is called right away. | The rules every adapter follows are documented on the `HttpAdapter` interface, and checked by the [conformance suite](https://dotpress.dev/services/testing.md#writing-an-adapter). --- url: https://dotpress.dev/reference/routes.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Routes and groups `defineRoute()`, `createRouteGroup()`, `createRouter()` and `defineMiddleware()`. For a guide, see [Routes](https://dotpress.dev/routing/routes.md), [Route groups](https://dotpress.dev/routing/groups.md) and [Middlewares](https://dotpress.dev/routing/middlewares.md). ```ts import { createRouter, defineMiddleware, notFoundError } from '@dotpress/core' interface Tenant { id: string } declare const tenants: { find(slug: string): Promise } declare const projects: { find(tenantId: string, id: string): Promise<{ id: string; name: string } | undefined> } const loadTenant = defineMiddleware<{ tenant: Tenant }>(async (ctx) => { const tenant = await tenants.find(ctx.req.params.tenant) if (!tenant) return notFoundError('Tenant not found') Object.assign(ctx, { tenant }) }) export const router = createRouter() const tenantRoutes = router.createGroup('/tenants/:tenant', [loadTenant]) tenantRoutes.defineRoute({ path: '/projects/:id', schema: (z) => ({ response: z.object({ id: z.string(), name: z.string() }) }), meta: { summary: 'Get a project', tags: ['projects'], responses: { 404: 'Not found' } }, handler: async ({ req, tenant }) => (await projects.find(tenant.id, req.params.id)) ?? notFoundError(), }) ``` ## defineRoute() ```ts function defineRoute(config: RouteConfig): void ``` Declares a route on the global router. `router.defineRoute()` and `group.defineRoute()` take the same configuration. | Option | Type | Default | Description | | ------------- | ----------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `path` | `string` | required | Starts with `/`. Static segments and `:param` segments only. | | `method` | `HttpMethod` | `'get'` | `get`, `post`, `put`, `patch`, `delete`, `head` or `options`, in lowercase. `ctx.req.method` is in uppercase, as sent by the client (`'POST'`). | | `handler` | `(ctx) => result` | required | Receives the [context](https://dotpress.dev/reference/context.md), returns the response: a value, a [response helper](https://dotpress.dev/reference/responses.md#response-helpers) or an [`HttpError`](https://dotpress.dev/reference/responses.md#httperror). Can be `async`. | | `schema` | `RouteSchema \| (z) => RouteSchema` | — | Zod schemas: see [Schema](#schema). Declare it before `handler`, so the handler is typed from it. | | `middlewares` | `Middleware[]` | `[]` | Run after the global and group middlewares. | | `status` | `number` | `200` | Status of a success. `204` when the handler returns `undefined`. | | `meta` | `RouteMeta` | `{}` | Documentation: see [Metadata](#metadata). | | `bodyLimit` | `number` | the adapter limit | Maximum body size, in bytes. | | `rawBody` | `boolean` | `false` | Keeps the raw bytes of the body in `req.rawBody`, typed `Uint8Array`. | Unknown options are rejected, in `schema` and `meta` too: `middleware` instead of `middlewares` throws a `TypeError`. See [Options and durations](https://dotpress.dev/concepts/options.md). ### Paths | Path | `req.params` | | -------------------------- | ------------------------------- | | `/articles` | `{}` | | `/articles/:id` | `{ id: string }` | | `/orgs/:orgId/members/:id` | `{ orgId: string; id: string }` | Parameter names match `/^[A-Za-z_][A-Za-z0-9_]*$/`. Wildcards, optional parameters and regular expressions are rejected. Matching is case-sensitive, ignores trailing slashes, and prefers static segments: see [Paths](https://dotpress.dev/routing/routes.md#paths). ### Schema ```ts interface RouteSchema { params?: Schema query?: Schema body?: Schema files?: Schema response?: Schema } ``` Any Zod 4 schema, classic or mini. The request is validated after the middlewares, and before the handler: `req.params`, `req.query`, `req.body` and `req.files` hold the parsed values, typed by the output of the schemas. An invalid request gets a `400 VALIDATION_FAILED`, with every issue. The response is parsed with `schema.response` (unknown keys of objects are stripped); a value that does not match is a `500`, logged. See [Validation](https://dotpress.dev/routing/validation.md). `arrayOf(schema)` validates a field sent once or several times (query string, form fields, files) as an array: ```ts schema: (z) => ({ query: z.object({ tag: arrayOf(z.string()).default([]) }) }) ``` ### Metadata | Field | Type | Description | | ------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | | `summary`, `description` | `string` | Shown in the documentation. | | `tags` | `string[]` | Groups the routes in the documentation. | | `operationId` | `string` | The OpenAPI operation ID. | | `deprecated` | `boolean` | Marks the route as deprecated. | | `security` | `string[]` | Security schemes accepted, any of them. Defaults to those of the middlewares; `[]` marks the route as public. | | `hidden` | `boolean` | Leaves the route out of the documentation. | | `responses` | `Record` | Other responses: returned errors, or responses that are not JSON. | `meta` is used by [`@dotpress/openapi`](https://dotpress.dev/services/openapi.md), and available to plugins in `app.routes`. ## createRouteGroup() ```ts function createRouteGroup(prefix: string, middlewares?: Middleware[]): RouteGroup ``` Creates a group on the global router. `router.createGroup()` and `group.createGroup()` take the same arguments. | Member | Description | | ----------------------------------- | ---------------------------------------------------------------------- | | `defineRoute(config)` | Declares a route under the prefix, after the middlewares of the group. | | `createGroup(prefix, middlewares?)` | A nested group: prefixes and middlewares add up. | | `prefix` | The prefix of the group. | Parameters of the prefix (`/tenants/:tenant`) are typed in the routes of the group, and so are the context properties guaranteed by its middlewares. See [Route groups](https://dotpress.dev/routing/groups.md). ## createRouter() ```ts function createRouter(): Router ``` An isolated registry of routes, mounted with `createApp({ routers })`. | Member | Description | | ----------------------------------- | ------------------------------------------------------------------ | | `defineRoute(config)` | Declares a route. | | `createGroup(prefix, middlewares?)` | Creates a group. | | `addResponseFilter(filter)` | A filter applied to the JSON results of the routes of this router. | | `clear()` | Removes every route and filter. | `globalRouter` is the router of `defineRoute()`, `createRouteGroup()` and `addResponseFilter()`, mounted when `createApp()` has no `routers`. ## defineMiddleware() ```ts function defineMiddleware( middleware: (ctx: RequestContext) => MiddlewareResult | Promise, options?: { security?: string[] } ): Middleware ``` A middleware returns nothing to continue, or an `HttpError` or a response to stop the request. Throwing an `HttpError` works too. | Parameter | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TProvides` | The context properties the middleware guarantees: `defineMiddleware<{ tenant: Tenant }>` types `ctx.tenant` as `Tenant` in the handlers of its routes. The middleware must set them, or return an error. | | `options.security` | Security schemes of the middleware (`['bearerAuth']`): its routes are documented as secured by them. | A plain function `(ctx) => …` is a middleware too, without guarantees. Middlewares run **before** validation: `ctx.req` holds the raw values. See [Middlewares](https://dotpress.dev/routing/middlewares.md). ## Response filters ```ts type ResponseFilter = (ctx: RequestContext, result: unknown) => unknown | Promise ``` A filter transforms the JSON result of a success, after the response validation. Filters run in this order: those of `createApp({ responseFilters })`, of the plugins, then of the router (`router.addResponseFilter()`, or `addResponseFilter()` for the global router). Errors and other response helpers do not go through filters. See [Response filters](https://dotpress.dev/routing/middlewares.md#response-filters). --- url: https://dotpress.dev/reference/context.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Request context The `ctx` object received by middlewares and handlers, and its `req` and `res`. For an introduction, see [The request context](https://dotpress.dev/concepts/context.md). ## RequestContext | Key | Type | Description | | ------------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `req` | `DotpressRequest` | The request: see [req](#req). | | `res` | `DotpressResponse` | The status, headers and cookies of the response: see [res](#res). | | `requestId` | `string` | The ID of the request, also sent in the `X-Request-ID` header. | | `logger` | `Logger` | A logger bound to the request: every line carries the `requestId`. | | `raw` | `unknown` | The native request of the adapter (Express `req`, Fastify request, Hono context, Lambda event). An escape hatch. | | `publicPath(path)` | `(path: string) => string` | The path seen by the browser, with the `basePath` or `publicBasePath` of the app. | In a handler, `ctx` also holds the properties guaranteed by the [typed middlewares](https://dotpress.dev/reference/routes.md#definemiddleware) of the route and its groups. ## Keys added by plugins | Key | Type | Plugin | | -------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `user` | `AuthUser \| undefined` | [`authPlugin`](https://dotpress.dev/auth/index.md): the authenticated user. Typed `AuthUser` after `requireAuth`. | | `auth` | `AuthSession \| undefined` | `authPlugin`: the token of the user, `userId`, `username`, `accessTokenId`, `sessionId`, `clientId`, `roles`, `claims`. Typed `AuthSession` after `requireAuth`. | | `memo` | `Memo` | [`cachePlugin`](https://dotpress.dev/services/cache.md): the memo of the request. | | `cache` | `Cache` | `cachePlugin({ cache })`: the cache, with the request logger. | | `events` | `EventBus` | [`eventsPlugin`](https://dotpress.dev/services/events.md): the bus, with the request logger and `requestId`. | | `mailer` | `Mailer` | [`mailerPlugin`](https://dotpress.dev/services/mailer.md): the mailer, with the request logger. | Plugin keys are computed on first access, at most once per request. Using the key of a plugin that is not installed throws: ```text "ctx.mailer" is used, but the "mailerPlugin" plugin is not installed in createApp(). ``` ## req | Member | Type | Description | | -------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `method` | `string` | Uppercase: `'GET'`, `'POST'`… | | `path` | `string` | Without the query string. | | `url` | `string \| undefined` | The full URL, when the adapter knows it. | | `params` | typed | Path parameters: from the path, or from `schema.params`. | | `query` | typed | Query string: `Record` without schema, repeated keys giving arrays. | | `body` | typed | The parsed body: `unknown` without schema, `undefined` when there is none. | | `files` | typed | Files of a `multipart/form-data` body, as `File` objects. Empty otherwise. | | `headers` | `Record` | Lowercase names. Repeated headers are joined with `, `. | | `header(name)` | `(name: string) => string \| undefined` | A header, case-insensitive. | | `cookies` | `Record` | The cookies of the request, decoded. | | `ip` | `string \| undefined` | The client address, as given by the server. Proxy headers count only when the server trusts them. See [Client IP address](https://dotpress.dev/routing/http-options.md#client-ip-address-behind-a-proxy). | | `rawBody` | `Uint8Array \| undefined` | The raw bytes of the body, on `rawBody: true` routes only (`Uint8Array` there). | | `signal` | `AbortSignal` | Aborted when the client disconnects: pass it to long work. | :::warning Middlewares see the raw request Middlewares run before validation: `ctx.req.params`, `query` and `body` hold the raw values, typed as such. Handlers receive the parsed values. ::: Request bodies are parsed by content type: JSON (`application/json`, `*+json`), forms (`application/x-www-form-urlencoded`, `multipart/form-data`), text (`text/*`, as a string), anything else as bytes. See [Bodies and file uploads](https://dotpress.dev/routing/bodies.md). ## res `ctx.res` never writes the body: the handler returns it. Every method returns `res`, so calls can be chained. | Member | Description | | ---------------------------------- | ----------------------------------------------------------------------- | | `setStatus(status)` | The status of the response, between 100 and 599. | | `statusCode` | The status set with `setStatus()`, or `undefined`. | | `setHeader(name, value)` | Sets a header, replacing its values. `value` can be an array. | | `appendHeader(name, value)` | Adds a value to a header. | | `getHeader(name)` | A header set on the response. | | `removeHeader(name)` | Removes a header. | | `setCookie(name, value, options?)` | Adds a `Set-Cookie` header. The value is URI-encoded. | | `clearCookie(name, options?)` | Expires a cookie. Pass the same `path` and `domain` as when it was set. | Headers and cookies set on `res` are kept on the response, including an `HttpError` returned or thrown later; an unexpected error gives a `500` without them. ### Status The status of a JSON response is, in this order: the `status` of `json(data, { status })`, then `res.setStatus()`, then the `status` of the route, then `200`. A handler returning `undefined` gets `204`, unless a status is set. ### Cookie options ```ts ctx.res.setCookie('session', token, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 24 * 7, }) ``` | Option | Type | Description | | ------------- | ----------------------------- | --------------------------------------------------------------------------------------- | | `httpOnly` | `boolean` | Hidden from JavaScript in the browser. Use it for every session cookie. | | `secure` | `boolean` | Sent over HTTPS only. | | `sameSite` | `'strict' \| 'lax' \| 'none'` | When the browser sends the cookie with cross-site requests. `'none'` requires `secure`. | | `maxAge` | `number` | Lifetime, in seconds. | | `expires` | `Date` | Expiry date. | | `path` | `string` | `/` by default. | | `domain` | `string` | Domain of the cookie. Without it, the host only. | | `partitioned` | `boolean` | A partitioned cookie (CHIPS). | | `priority` | `'low' \| 'medium' \| 'high'` | Priority of the cookie. | See [Cookies](https://dotpress.dev/routing/http-options.md#cookies), and [Cookie mode](https://dotpress.dev/auth/cookies.md) for authentication. ## Extending the context Declare a key with module augmentation, then provide it from a plugin with `api.decorateContext()`, or set it in a middleware: ```ts declare module '@dotpress/core' { interface RequestContext { services: AppServices } } declareContextKey('services', 'servicesPlugin') ``` `declareContextKey(key, pluginName)` makes the key throw an explicit error when the plugin is not installed. The keys of the core (`req`, `res`, `requestId`, `logger`, `raw`, `publicPath`) cannot be decorated. See [Adding your own keys](https://dotpress.dev/concepts/context.md#adding-your-own-keys). --- url: https://dotpress.dev/reference/responses.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Responses and errors What a handler returns: values, response helpers and errors. For a guide, see [Responses](https://dotpress.dev/routing/responses.md) and [Errors](https://dotpress.dev/routing/errors.md). ## What a handler returns | Value | Response | | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | A value (object, array, string, number…) | JSON, with the status of the route (`200` by default). Validated by `schema.response`, then filtered. | | `undefined` | `204 No Content`, or the status set with `res.setStatus()` or the route `status`. | | `json(data, init)` | JSON with an explicit status or headers. Validated and filtered like a value. | | `text()`, `redirect()`, `stream()`, `sse()`, `file()`, `empty()` | Sent as is: no response validation, no filters. | | An `HttpError` | The error response. Returning it or throwing it gives the same response. | | Anything thrown, except an `HttpError` | `500 INTERNAL_ERROR`, logged and passed to `onError`. | ## Response helpers All of them are exported by `@dotpress/core`. `init` accepts `status` and `headers`; headers set on `ctx.res` are merged. | Helper | Response | | ------------------------------------------- | -------------------------------------------------------------------------------------------- | | `json(data, init?)` | JSON. | | `text(body, init?)` | Plain text, `text/plain; charset=utf-8` unless a `content-type` header is given. | | `redirect(location, { status?, headers? })` | A redirect, `302` by default: `301`, `302`, `303`, `307` or `308`. | | `stream(source, init?)` | A streamed body. `init.contentType` defaults to `application/octet-stream`. | | `sse(source, init?)` | Server-Sent Events. `init.heartbeat` in milliseconds, `15000` by default, or `false`. | | `file(body, init?)` | A download: `filename`, `contentType`, `disposition` (`attachment` by default, or `inline`). | | `empty(init?)` | No body, `204` by default. | ```ts handler: ({ req, res }) => { res.setHeader('Cache-Control', 'no-store') return json(created, { status: 201, headers: { Location: `/tasks/${created.id}` } }) } ``` `redirect()` sends the location as given: behind a proxy, build it with `ctx.publicPath('/login')`. ### stream() The source is a `ReadableStream`, an iterable, an async iterable, or a function returning one. A function receives `{ signal }`, aborted when the client disconnects. Chunks are strings, encoded as UTF-8, or `Uint8Array`. A string or a `Uint8Array` given as the source is one chunk. ```ts return stream(async function* ({ signal }) { for await (const row of db.export({ signal })) yield `${row.csv}\n` }, { contentType: 'text/csv' }) ``` ### sse() The source yields events, or strings sent as `data`: | Field | Description | | --------- | --------------------------------------------------------------- | | `data` | The payload. Strings are sent as is, other values as JSON. | | `event` | The type of the event, `message` on the client by default. | | `id` | Sent back by the browser as `Last-Event-ID` when it reconnects. | | `retry` | Reconnection delay for the browser, in milliseconds. | | `comment` | A comment line, ignored by the browser. | `sse()` sets `Content-Type: text/event-stream`, `Cache-Control: no-cache` and `X-Accel-Buffering: no` (no buffering in nginx). ### file() `body` is a `Uint8Array`, an `ArrayBuffer`, a `Blob` or a `ReadableStream`. The content type defaults to the type of the `Blob`, else `application/octet-stream`. `Content-Length` is set when the size is known, and `filename` is encoded for non-ASCII names. ```ts return file(pdf, { filename: 'invoice-2026-001.pdf', contentType: 'application/pdf' }) ``` ## Error helpers Each one returns an `HttpError`: `return notFoundError()` or `throw notFoundError()`. `message` replaces the default message. The options: | Option | Description | | ------- | ------------------------------------------------------------------------------- | | `data` | Details added to the body: `notFoundError('Task not found', { data: { id } })`. | | `cause` | The original error (`error.cause`), for the logs and `onError`. Never sent. | Unknown options are rejected: `notFoundError('Task not found', { id })` throws a `TypeError`. | Helper | Status | `error` code | Default message | | ------------------------------------------------ | ------ | ---------------------- | --------------------- | | `badRequestError(message?, options?)` | 400 | `BAD_REQUEST` | Bad Request | | `unauthorizedError(message?, options?)` | 401 | `UNAUTHORIZED` | Unauthorized | | `forbiddenError(message?, options?)` | 403 | `FORBIDDEN` | Forbidden | | `notFoundError(message?, options?)` | 404 | `NOT_FOUND` | Not Found | | `conflictError(message?, options?)` | 409 | `CONFLICT` | Conflict | | `unprocessableError(message?, options?)` | 422 | `UNPROCESSABLE_ENTITY` | Unprocessable Entity | | `tooManyRequestsError(message?, options?)` | 429 | `TOO_MANY_REQUESTS` | Too Many Requests | | `internalError(message?, options?)` | 500 | `INTERNAL_ERROR` | Internal Server Error | | `errorResponse(status, code, message, options?)` | any | any | — | ### Errors produced by Dotpress | Status | `error` code | When | | ------ | ------------------------ | ------------------------------------------------------------------------------------ | | 400 | `VALIDATION_FAILED` | The request does not match the schema of the route. `data.issues` lists every issue. | | 400 | `MALFORMED_BODY` | The body cannot be parsed: invalid JSON, UTF-8 or multipart. | | 404 | `NOT_FOUND` | No route matches the path (`Route not found`). | | 405 | `METHOD_NOT_ALLOWED` | The path exists for other methods. The `Allow` header lists them. | | 413 | `PAYLOAD_TOO_LARGE` | The body exceeds the limit of the route or of the adapter. | | 415 | `UNSUPPORTED_MEDIA_TYPE` | A `Content-Encoding` other than `identity`, or an unknown charset. | | 500 | `INTERNAL_ERROR` | An unexpected error, or a response that does not match `schema.response`. | Validation issues have this shape: ```ts interface ValidationIssue { source: 'params' | 'query' | 'body' | 'files' path: (string | number)[] code: string // the Zod issue code: 'invalid_type', 'too_small'… message: string } ``` ## Error body Every error response has the same JSON body: ```ts interface ErrorBody { status: number error: string message: string data?: Record } ``` ```json { "status": 404, "error": "NOT_FOUND", "message": "Task not found" } ``` With `exposeErrors: true`, the `data` of a `500` holds the `name`, `message` and `stack` of the error, and the `issues` of an invalid response. Never in production. ## HttpError ```ts class HttpError extends Error { constructor( status: number, // 400 to 599 code: string, message: string, options?: { data?: Record; cause?: unknown } ) readonly status: number readonly code: string readonly data: Record | undefined toJSON(): ErrorBody } ``` Subclass it, or wrap `errorResponse()`, for the errors of your domain: ```ts export const quotaExceededError = (limit: number) => errorResponse(402, 'QUOTA_EXCEEDED', 'Quota exceeded', { data: { limit } }) ``` `isHttpError(value)` recognizes an `HttpError`, even one created by another copy of `@dotpress/core`. `toErrorBody(error)` returns its body. Headers set on `ctx.res` are kept on the response of an `HttpError`, not on the `500` of an unexpected error. See [Custom errors](https://dotpress.dev/routing/errors.md#custom-errors) and [Unexpected errors](https://dotpress.dev/routing/errors.md#unexpected-errors). --- url: https://dotpress.dev/reference/plugins.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Plugin API `definePlugin()`, the API given to `setup()`, and the hooks. For a guide, see [Plugins](https://dotpress.dev/routing/plugins.md). ```ts import { definePlugin } from '@dotpress/core' interface Metrics { observe(name: string, value: number, labels: Record): void } export const metricsPlugin = (metrics: Metrics) => definePlugin({ name: 'metrics', setup(api) { api.hooks.onResponse(({ route, response, duration }) => { metrics.observe('http_request_duration_ms', duration, { route: route ? `${route.method.toUpperCase()} ${route.path}` : 'unmatched', status: String(response.status), }) }) }, }) ``` ## definePlugin() ```ts function definePlugin(plugin: T): T interface Plugin { readonly name: string readonly dependsOn?: readonly string[] setup(api: PluginAPI): void | Promise } ``` | Member | Description | | ------------ | --------------------------------------------------------------------------------------- | | `name` | Unique in the app. Used by `dependsOn` and `api.getPlugin()`. | | `dependsOn` | Names of plugins set up before this one. A missing one makes `createApp()` fail. | | `setup(api)` | Registers the features of the plugin. Called once, in dependency order. Can be `async`. | Extra properties are allowed, and readable by other plugins with `api.getPlugin()`. By convention, a plugin is exported as a function that takes its options: `cachePlugin({ cache })`. The plugins of Dotpress are named `auth`, `cache`, `events`, `mailer` and `openapi`: `dependsOn: ['auth']`. ## PluginAPI The registration methods work during `setup()` only: called later, they throw. | Member | Description | | ----------------------------------- | --------------------------------------------------------------------------------------- | | `defineRoute(config)` | Declares a route, like `defineRoute()`. | | `createGroup(prefix, middlewares?)` | Creates a group, like `createRouteGroup()`. | | `addGlobalMiddleware(middleware)` | A middleware run on every route, before those of `createApp()`. | | `addResponseFilter(filter)` | A filter applied to every JSON success, after those of `createApp()`. | | `decorateContext(key, factory)` | Provides `ctx[key]`: see [Context keys](#context-keys). | | `onError(hook)` | Called with unexpected errors, like the `onError` option. | | `hooks` | The [lifecycle and request hooks](#hooks). | | `name` | The name of the plugin. | | `logger` | A logger bound to the plugin (`plugin` field). | | `basePath`, `publicBasePath` | The options of the app, normalized, or `''`. | | `publicPath(path)` | The path seen by the browser: for a cookie `Path` or a documentation URL. | | `cors` | The CORS settings: `credentials`, and `isOriginAllowed(req)`. `undefined` without CORS. | | `getRoutes()` | The mounted routes (`RouteInfo[]`). From the `onInit` hook, or at request time. | | `getPlugin(name)` | Another plugin, or `undefined`. | | `getPlugins()` | Every plugin, in setup order. | ## Hooks | Hook | Signature | When | | ------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------- | | `onInit` | `() => void \| Promise` | Every plugin is set up and the routes are compiled. `getRoutes()` is available. | | `onReady` | `() => void \| Promise` | The routes are mounted on the adapter, before `listen()`. | | `wrapRequest` | `(ctx, next) => Promise` | Runs the rest of the request inside the hook: must call `next()` and return its result. | | `onRequest` | `(ctx) => MiddlewareResult` | Each request matching a route, before the middlewares. Returning an error or a response stops it. | | `onResponse` | `(event) => void \| NormalizedResponse` | Each response, `404`, `405` and adapter errors included. Returning a response replaces it. | | `onClose` | `() => void \| Promise` | `app.close()`, after the server is stopped. Plugins set up last close first. | `onInit` and `onReady` run inside `createApp()`: a failure makes it reject. The hooks of several plugins run in setup order; for `wrapRequest`, the first plugin is the outermost. ### The response event | Field | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `request` | The normalized request. | | `response` | The normalized response: `status`, `headers`, `body`. | | `requestId` | The ID of the request. | | `ctx` | The context, `undefined` when no route matched. | | `route` | The route (`RouteInfo`), `undefined` when no route matched. | | `duration` | Time spent producing the response, in milliseconds, without the streamed body. Unlike the options, which take seconds, it is in milliseconds, as most metrics and logs expect. | ### Order in a request 1. CORS preflight requests are answered. 2. No route: `404` or `405`, then `onResponse`. 3. The request ID and the request logger are created. 4. `wrapRequest`, then `onRequest`. 5. The middlewares: plugins, `createApp()`, groups, route. 6. Request validation, the handler, response validation. 7. The response filters: `createApp()`, plugins, router. 8. CORS headers, then `onResponse`. See [The request pipeline](https://dotpress.dev/concepts/request-pipeline.md). ## Context keys ```ts declare module '@dotpress/core' { interface RequestContext { tenant: TenantService } } declareContextKey('tenant', 'tenantPlugin') export const tenantPlugin = (tenants: TenantService) => definePlugin({ name: 'tenant', setup(api) { api.decorateContext('tenant', (ctx) => tenants.withLogger(ctx.logger)) }, }) ``` - **`api.decorateContext(key, factory)`**: the factory receives the context, and runs on first access, at most once per request. Two plugins cannot provide the same key, and the keys of the core (`req`, `res`, `requestId`, `logger`, `raw`, `publicPath`) are reserved. - **`declareContextKey(key, pluginName)`**: at the top level of the module, next to the augmentation. Without the plugin, `ctx.tenant` throws `"ctx.tenant" is used, but the "tenantPlugin" plugin is not installed in createApp().` ## Plugin or middleware? A middleware is enough for logic attached to some routes. Write a plugin when the feature needs routes of its own, a context key, a hook on every response, or code at startup and shutdown. See [Plugin or middleware?](https://dotpress.dev/routing/plugins.md#plugin-or-middleware). --- url: https://dotpress.dev/reference/auth.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Auth The settings, routes, errors and contracts of `@dotpress/auth`. For a guide, see [Authentication](https://dotpress.dev/auth/index.md). ## createAuth() ```ts import { createAuth } from '@dotpress/auth' const auth = createAuth({ keys, issuer: 'https://api.example.com', dataProvider }) ``` | Setting | Default | Description | | --------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `keys` | required | `privateKey` (PKCS#8 PEM) and `publicKey` (SPKI PEM), plus optional `kid` and `additionalPublicKeys`. RS256. See [Keys and rotation](https://dotpress.dev/auth/keys.md). | | `issuer` | required | The `iss` claim, checked on every request: the URL of the API, one value per environment and application. | | `dataProvider` | required | The storage of users and refresh tokens: see [DataProvider](#dataprovider). | | `audience` | `issuer` | The `aud` claim: the API that accepts the tokens. Checked on every request. | | `accessTokenTTL` | `'15m'` | Lifetime of the access tokens. | | `session.idleTimeout` | `'14d'` | The session ends when it is not refreshed during this delay. | | `session.absoluteTimeout` | none | The session ends this delay after login, even when active. | | `clients` | — | `{ allowed, required?, isUserRoleAllowed?({ userId, role, clientId }), sessions? }`: see [Clients](https://dotpress.dev/auth/clients.md). | | `cookies` | disabled | The cookie mode: see [Cookie settings](#cookie-settings). | | `loginThrottle` | enabled, in memory | `{ store?, limits? }`, or `false`. See [Brute force protection](https://dotpress.dev/auth/passwords.md#brute-force-protection). | | `beforeLogin` | — | `({ username, clientId, ipAddress, req }) => …`, after the throttle and before the password check. Return an `HttpError` to reject the attempt. | | `onLoginSuccess` | — | Called with `{ userId, username, clientId, ipAddress }`. | | `onLoginFailed` | — | Called with `{ username, errorType, clientId, ipAddress }`. `errorType`: `invalid_username`, `invalid_password`, `invalid_role` or `too_many_attempts`. | | `passwordHashRounds` | `12` | bcrypt cost of `hashPassword()`, and of the dummy hash compared for unknown users. | | `usernameClaim` | `false` | Writes the `username` claim in the access tokens. | | `getUserRoles` | `user.roles`, or `user.role` | The roles checked by `requireRole()`. | | `refreshTokenReuseInterval` | `'10s'` | Delay after its first use during which a refresh token presented again gets a new pair in the same session. `0` disables it. | | `onRefreshTokenReuse` | — | Called with `{ userId, sessionId, accessTokenId }` when a session is revoked because a used refresh token came back. | The durations are [`Duration` values](https://dotpress.dev/concepts/options.md#durations), rounded to the second: a number of seconds, or a string like `'15m'` or `'14d'`. Invalid or unknown settings make `createAuth()` throw; a missing `issuer`, a `publicKey` that does not match the `privateKey`, or a PKCS#1 key make the app fail at startup, with an explicit message. ### Cookie settings | Setting | Default | Description | | ---------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled` | `false` | Enables the cookie mode: login with `mode: 'cookie'`. | | `accessTokenInCookie` | `false` | Also sets the access token as a cookie. Recommended for browsers. | | `httpOnly` | `true` | Hides the cookies from the JavaScript of the page. | | `secure` | `true` | HTTPS only. Chrome and Firefox accept secure cookies on `http://localhost`, Safari does not: see [Cookies](https://dotpress.dev/auth/cookies.md#the-cookies). | | `sameSite` | `'lax'` | `SameSite` of the access token cookie. | | `refreshTokenSameSite` | `'strict'` | `SameSite` of the refresh token cookie; `'none'` when `sameSite` is `'none'`. | | `trustedOrigins` | the `cors` origins with credentials, else `[]` | Other origins allowed to send authenticated cookie requests. | | `domain` | — | Domain of the cookies. Without it, the host only. | | `path` | `'/'` | Path of the access token cookie. | | `refreshTokenPath` | the path of the auth routes | Path of the refresh token cookie. | | `accessTokenName` | `__Host-dotpress_access_token` | Name of the access token cookie. | | `refreshTokenName` | `__Secure-dotpress_refresh_token` | Name of the refresh token cookie. | See [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md). ## authPlugin() ```ts authPlugin(auth, { prefix: '/auth', routes: true, jwks: false }) ``` | Option | Default | Description | | -------- | --------- | ---------------------------------------------------------------------------- | | `prefix` | `'/auth'` | Prefix of the routes. | | `routes` | `true` | `false` keeps only the authentication of the requests. | | `jwks` | `false` | Publishes the public keys at `GET /.well-known/jwks.json`, cached 5 minutes. | The plugin is named `auth`, provides `ctx.user` and `ctx.auth`, and declares the `bearerAuth` security scheme (`AUTH_SECURITY_SCHEMES`) for OpenAPI. ### Routes | Route | Body | Response | | -------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `POST /auth/login` | `{ username, password, clientId?, mode? }` | The tokens (see below), `userId`, `expiresIn`, `expiresAt`, `sessionExpiresAt?` | | `POST /auth/refresh` | `{ accessToken, refreshToken }`, or cookies | A new pair, same fields | | `GET /auth/me` | — | The user (`AuthUser`) | | `POST /auth/restore` | — (cookies) | `userId`, `user`, `expiresIn`, `expiresAt`, `sessionExpiresAt?`. Requires `cookies.accessTokenInCookie`. | | `POST /auth/logout` | `{ refreshToken?, scope? }` | `200`, and the cookies cleared | | Configuration | Cookies | Tokens in the body | | ------------------------------------------------------------------------- | ------------- | ----------------------------- | | Body mode | — | `accessToken`, `refreshToken` | | `cookies: { enabled: true }`, `mode: 'cookie'` | refresh token | `accessToken` | | `cookies: { enabled: true, accessTokenInCookie: true }`, `mode: 'cookie'` | both | none | `expiresAt` is the expiration of the access token; `sessionExpiresAt` is set when an absolute timeout applies. ### Errors The routes answer the standard error format. The `error` field holds the code, typed `AuthRouteErrorCode`: test it, or the status. The `message` is a sentence for people, and may change. ```json { "status": 401, "error": "EXPIRED_REFRESH_TOKEN", "message": "The session has expired. Log in again." } ``` | Status | `error` | When | | ------ | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `400` | `VALIDATION_FAILED` | Invalid body, or a `clientId` outside `clients.allowed` | | `401` | `INVALID_LOGIN` | Unknown username, wrong password, account without password, or a role not allowed for the client | | `429` | `TOO_MANY_LOGIN_ATTEMPTS` | Over a limit of the login throttle, with `Retry-After` | | `401` | `NO_TOKENS_PROVIDED` | `/auth/refresh` without tokens, in the body or as cookies | | `401` | `INVALID_REFRESH_TOKEN` | Unknown, revoked or reused refresh token, an access token that does not match, or a user `findUserById()` no longer returns | | `401` | `EXPIRED_REFRESH_TOKEN` | The session reached its inactivity or absolute timeout | | `401` | `COOKIES_NOT_ENABLED`, `ACCESS_TOKEN_NOT_IN_COOKIE` | `/auth/restore` without the cookie mode, or without `accessTokenInCookie` | | `401` | `NO_REFRESH_TOKEN`, `NO_ACCESS_TOKEN` | `/auth/restore` without one of the cookies | | `403` | `CROSS_ORIGIN_REQUEST` | A cookie request from an untrusted origin, on `/auth/refresh`, `/auth/restore` or `/auth/logout` | | `401` | `UNAUTHORIZED` | `/auth/logout` with `scope: 'all'`, without a valid access token or an active refresh token | Outside the routes, the service throws an `AuthError` whose `code` is `INVALID_ACCESS_TOKEN`, `INVALID_REFRESH_TOKEN`, `EXPIRED_REFRESH_TOKEN`, `REFRESH_TOKEN_REUSED` or `SESSION_REVOKED`. ## Guards | Middleware | Answers | Guarantees | | ----------------------------- | ------------------------------------------------------- | --------------------------------------------- | | `requireAuth` | `401` without user | `ctx.user: AuthUser`, `ctx.auth: AuthSession` | | `requireRole(...roles)` | `401` without user, `403` without one of the roles | the same | | `requireClient(...clientIds)` | `401` without user, `403` for a token of another client | the same | A `401` gets a `WWW-Authenticate: Bearer` header (RFC 6750), with `error="invalid_token"` when the request carried an expired, revoked or invalid token. See [Protecting routes](https://dotpress.dev/auth/protecting-routes.md). ## The service | Method | Description | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `generateTokensForUser({ userId, username?, clientId? })` | Generates and stores a token pair, starting a session. | | `refreshTokens({ accessToken, refreshToken })` | Rotates a pair. Returns the new pair, `userId` and `user`. | | `verifyAccessToken(accessToken)` | Verifies a valid access token, and returns its `AuthSession`. | | `revokeSession(refreshToken, { scope? })` | Revokes the session of a refresh token, or every session of the user with `scope: 'all'`. Returns `{ userId, sessionId }`, or `undefined` when nothing was revoked. | | `revokeUserSessions(userId)` | Revokes every session of a user, on every device: after a password change, or when an account is disabled. | | `hashPassword(password)` | bcrypt hash, with `passwordHashRounds`. Throws a `RangeError` beyond 72 bytes. | | `verifyPassword(password, hash)` | Compares with bcrypt; a missing hash (unknown user, account without password) is compared with a dummy one, in the same time, and gives `false`. | | `passwordNeedsRehash(hash)`, `rehashPassword(password)` | Upgrade the cost of a hash. | | `setAuthCookies(res, tokens)`, `clearAuthCookies(res)` | Set or clear the cookies, in a route. | | `isCookieAuthenticationAllowed(req)` | `Promise`: the protection against cross-site requests of the plugin. | | `getSessionExpiresAt(session)` | End of a session with an absolute timeout. | | `getJwks()` | The public keys, as a JSON Web Key Set. | | `getUserRoles(user)` | The roles of a user. | `generatePasswordHash(password, { rounds? })` and `isPasswordTooLong(password)` are also exported, without a service. ## AuthSession `ctx.auth`, the data of the access token: | Field | Claim | Description | | --------------- | ----------- | --------------------------------------------------- | | `userId` | `sub` | The user. | | `accessTokenId` | `jti` | The access token. | | `sessionId` | `sid` | The session: the `sessionId` of its refresh tokens. | | `clientId` | `client_id` | The client, with the `clients` setting. | | `username` | `username` | With `usernameClaim: true` only. | | `roles` | — | The roles of the user. | | `claims` | — | Every claim of the token. | Access tokens follow RFC 9068: `typ: at+jwt`, RS256, and the `iss`, `aud`, `sub`, `jti`, `iat`, `exp` and `auth_time` claims. `auth_time` is the start of the session. ## DataProvider ```ts interface DataProvider { storeRefreshToken(payload: { token: string tokenHash: string // SHA-256 of the token: store this one only userId: string accessTokenId: string // the access token issued with it sessionId: string // the session expiresAt: Date }): Promise findRefreshToken(tokenHash: string): Promise< | { userId: string accessTokenId: string sessionId?: string | null expiresAt: Date isUsed: boolean usedAt?: Date | null revokedAt?: Date | null } | undefined > markRefreshTokenAsUsed(tokenHash: string, usedAt: Date): Promise revokeUserTokens(userId: string): Promise // every session of a user revokeSessionTokens(sessionId: string): Promise // one session findUserById(userId: string): Promise // undefined for deleted or disabled accounts findUserIdentifiers(username: string): Promise< { userId: string; passwordHash: string | null; role?: string } | undefined > isSessionRevoked?(sessionId: string): Promise // optional: immediate revocation updatePasswordHash?(userId: string, passwordHash: string): Promise // optional: hash upgrade } ``` `isUsed` can be derived from `usedAt`. Refresh tokens are 128 random bytes; only their hash is stored. See [Data provider](https://dotpress.dev/auth/data-provider.md). --- url: https://dotpress.dev/reference/events.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Events The definitions, options, errors and contracts of `@dotpress/events`. For a guide, see [Events and workers](https://dotpress.dev/services/events.md); for each queue, [Event workers](https://dotpress.dev/deployment/event-workers.md). ## defineEvent() ```ts defineEvent({ name: 'invoice.paid', schema: z.object({ invoiceId: z.string() }), transport: 'edge' }) ``` | Option | Description | | ----------- | --------------------------------------------------------------------------------------------------- | | `name` | Letters, digits, `.`, `_`, `:` and `-`. | | `schema` | Zod schema of the payload. The payload is serialized as JSON, then validated: describe JSON values. | | `transport` | Optional: the name of a transport of the bus, `default` otherwise. | ## defineListener() ```ts defineListener(invoicePaid, { name: 'send-receipt', handle: async (context) => { … } }) defineListener(invoicePaid, { name: 'send-receipt', load: () => import('./send-receipt.ts') }) ``` | Option | Description | | ----------- | ----------------------------------------------------------------------------------------------------- | | `name` | Unique: it identifies the listener in the messages. Renaming it orphans the messages still in queues. | | `handle` | The handler. | | `load` | Instead of `handle`: imports a module whose default export is the handler, in the workers only. | | `transport` | Optional: another transport than the one of its event. | The handler receives: | Field | Description | | ------------------- | --------------------------------------------------------------------- | | `payload` | The payload, parsed by the schema, transforms applied. | | `event`, `listener` | The names. | | `id` | The message: the same for every attempt. Use it to ignore duplicates. | | `emissionId` | The emission, shared by the messages of its listeners. | | `attempt` | The attempt number, from 1. | | `emittedAt` | The date of the emission. | | `metadata` | The metadata of the emission: `requestId` with the plugin. | | `logger` | The logger of the worker. | A handler throws to be retried. ## createEventBus() | Option | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `listeners` | Every listener of the app: the bus sends one message per listener of an emitted event. | | `transport` | The transport of every event. | | `transports` | Instead of `transport`: transports by name, `default` for the events without `transport`. | | `logger` | Any logger with `info`, `warn` and `error`, and optionally `debug`. Silent by default. | | `onFailure` | Failures of the listeners run by the `sync` and `memory` transports. | | `sendTimeout` | How long `emit()` waits for a transport: a number of seconds or a duration. 10 seconds by default; `false` waits without limit. Beyond it, the messages of the transport fail with an `EventSendTimeoutError`. The `sync` and `memory` transports are not limited. | The bus checks at startup that every listener has its transport. Names other than `default` are declared for type checking: ```ts declare module '@dotpress/events' { interface EventTransports { edge: true } } ``` ### emit() ```ts const { emissionId, messages } = await events.emit(event, payload, { emissionId, delay, metadata }) ``` | Option | Description | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `emissionId` | The identifier of the emission, random by default: the message ids derive from it. Emitting again with the same `emissionId` gives the same ids. It names one occurrence of the fact (`${order.id}:${order.version}`), not its entity. 1 to 200 characters, without control characters. | | `delay` | Delay before the listeners run, within the limit of the transport: a number of seconds, or a [duration](https://dotpress.dev/concepts/options.md#durations) like `'5m'`, rounded up to the second. | | `metadata` | Strings passed to the listeners. Keys: 1 to 128 characters among letters, digits, `.`, `_` and `-`; values on one line. | `messages` lists one `{ id, listener, transport }` per listener. An event without listeners is not sent. Without `emissionId`, each call is a new emission, with new message ids: emitting again after an `EventEmitError` runs again the listeners whose message was sent. `error.retry()` sends only the failed messages. `events.withContext({ logger, metadata })` returns a bus that logs with this logger and adds this metadata: `ctx.events` is one. `events.close()` closes the transports that have a `close()` (BullMQ, pg-boss, Service Bus), each one once, then throws the first error. `eventsPlugin()` calls it when the app closes. ## Transports in the process | Transport | Behavior | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `createSyncTransport()` | Runs the listeners inside `emit()`, which waits for them and throws an `EventEmitError` when one fails. Delays are ignored. | | `createMemoryTransport(options?)` | An in-process queue with retries. Messages are lost when the process stops. | | Option of the memory transport | Default | Description | | ------------------------------ | ---------------------------- | -------------------------------------------------------------------------------------------- | | `maxAttempts` | `3` | Attempts of a message. | | `retryDelay(attempt)` | 100 ms, doubled each attempt | Delay before a retry: a number of seconds, or a duration like `'100ms'`. `() => 0` in tests. | The memory transport has `sent` (the envelopes sent), `drain()` (waits for every message, retries included) and `clear()`. `createFakeEventBus()` checks each emission like a real bus (event, payload, delay, metadata) without running listeners, and records it in `emitted`; `clear()` empties it. See [Testing helpers](https://dotpress.dev/services/testing.md#events). ## createWorker() | Option | Description | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `listeners` | The listeners this worker runs. | | `logger` | The logger of the worker, given to the listeners: any logger with `info`, `warn` and `error`. The global `console` by default, from the `info` level. | | `onFailure(error, info)` | Called for every failure. Its own errors are logged and ignored. | | `maxAttempts` | The retry limit of the queue, so that the last attempt is reported as `final`. | `info` holds the `envelope` (undefined when the message is not one), the `attempt`, `final` (a dead message, or the last attempt), and the `reason`: | Reason | Result | Meaning | | --------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------- | | `listener-error` | `retry` | The listener threw. | | `unsupported-version` | `retry` | An envelope of a later version, emitted by a newer deployment: retried until a newer worker handles it (rolling deployments). | | `invalid-envelope` | `dead` | The message is not an envelope of Dotpress. | | `unknown-listener` | `dead` | The worker does not run this listener: usually a deployment mistake. | | `invalid-payload` | `dead` | The payload does not match the current schema of the event. | `worker.handle(message, { attempt })` returns `success`, `retry` or `dead`, and never throws: the entry points of the transports (Lambda handler, `queue()` handler…) are built on it. `startWorker(worker, source, { logger, signal })` reads a source until stopped (logging to the console without `logger`), and returns `{ stop(), done }`: `stop()` finishes the messages in progress, and `done` resolves when the worker has stopped, or rejects when the source failed. The module given to `dotpress-events work` exports a `WorkerEntry`: `{ worker, source, logger? }`. ## eventsPlugin() ```ts import { eventsPlugin } from '@dotpress/events/plugin' await createApp({ adapter, plugins: [eventsPlugin(events)] }) ``` The plugin, named `events`, provides `ctx.events`: the bus, with the request logger, and the `requestId` in the metadata. Using `ctx.events` without the plugin throws an explicit error. The transports of the bus are closed with the app (`events.close()`). ## Logs | Level | Message | | ------- | -------------------------------------------------------------------------------------------------------- | | `info` | `Event emitted` (event, emission id, number of messages); `Event worker started`, `Event worker stopped` | | `debug` | `Event emitted without listeners`; `Event listener succeeded` | | `warn` | `Event listener failed, the message is retried` | | `error` | `Event listener failed, the message is not retried`; `onFailure hook failed` | Payloads are never logged. ## Errors | Error | When | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TypeError` | Invalid options of `defineEvent()`, `defineListener()`, `createEventBus()`, `emit()`… | | `EventPayloadError` | At `emit()`: the payload does not match the schema, or is not serializable as JSON. Fields: `event`, `issues`. | | `EventEmitError` | Some messages could not be sent. Fields: `sent`, `failed`, `cause`. `retry()` sends the failed messages again, with the same ids: it resolves like `emit()`, or throws a new `EventEmitError` whose `sent` adds up the attempts. | | `EventSendTimeoutError` | In `EventEmitError#failed`: a transport did not answer within `sendTimeout`. Fields: `transport`, `timeout` (milliseconds). The send may still complete later. | | `PartialSendError` | For transport authors: some messages of a `send()` call failed. `failed` lists them: `{ id, error }`, by message id. | The error classes extend `EventsError`. ## Custom transports A transport has a `kind`, a `send(envelopes, { delay, signal })` method, where `delay` is a number of whole seconds and `signal` is aborted when the bus stops waiting (`sendTimeout`), and optionally `close()`. A source has a `kind` and a `consume(worker, { signal, logger })` method. Envelopes are plain JSON objects: ```ts { v: 1, id, emissionId, event, listener, payload, emittedAt, metadata } ``` Adding a field to the envelope keeps `v: 1`: workers ignore the fields they do not know. Only an incompatible change raises the version, and workers retry the envelopes of a later version until a newer worker handles them. --- url: https://dotpress.dev/reference/mailer.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Mailer The definitions, options, providers and errors of `@dotpress/mailer`. For a guide, see [Emails](https://dotpress.dev/services/mailer.md). ## defineTemplate() ```ts defineTemplate({ name: 'welcome', layout: baseLayout, schema: z.object({ firstName: z.string() }), subject: { en: 'Welcome, {{firstName}}', fr: 'Bienvenue, {{firstName}}' }, translations: { intro: { en: '…', fr: '…' } }, mjml: ({ t, locale }) => `…`, }) ``` | Option | Description | | -------------- | --------------------------------------------------------------------------------- | | `name` | Used in errors and logs. | | `layout` | Optional: a layout of the same format (MJML or HTML). | | `schema` | Optional Zod schema of the data. Without it, the template accepts no data. | | `subject` | A string, or one per locale. | | `translations` | Optional: texts by key, each with every locale. Read with `t(key)`. | | `mjml` | The MJML source: a string, or a function receiving `{ t, locale }`. | | `html` | Instead of `mjml`: the HTML source. MJML is then never loaded. | | `text` | Optional text version, a string or a function. Converted from the HTML otherwise. | Templates are checked when they are defined: unknown options, a missing source, texts without the same locales, or a layout without translations in a locale of the template throw a `TypeError`. `template.locales` lists the locales. ## defineLayout() ```ts defineLayout({ translations: { footer: { en: 'Sent by Example.', fr: 'Envoyé par Example.' } }, mjml: ({ t, content, locale }) => `${content}`, }) ``` | Option | Description | | ---------------- | ---------------------------------------------------------------------------------------------- | | `translations` | Optional: texts of the layout. The `t()` of a layout only reads its own translations. | | `mjml` or `html` | The source, a function receiving `{ t, content, locale }`: `content` is the rendered template. | In MJML, place `content` inside ``: templates provide `` elements. A layout without translations can be used in any locale. Reusable blocks are plain functions returning MJML. `mj-include` is ignored: templates do not read files. ## Rendering 1. The template function runs with `t()`, then the layout, which receives it as `content`. 2. MJML compiles the result to HTML, cached by template and locale. 3. Mustache inserts the data in the HTML, the subject and the text version. | Syntax | HTML version | Subject and text version | | ------------- | ------------------- | ------------------------ | | `{{value}}` | `& < > " '` escaped | as is | | `{{{value}}}` | as is | as is | `/`, `=` and `` ` `` are not escaped, unlike the default of Mustache: many email clients do not decode them in links. Mustache sections work (`{{#items}}…{{/items}}`); partials do not. The subject is a single line: line breaks become spaces. The text version, without a `text` source, is converted from the HTML by [html-to-text](https://github.com/html-to-text/node-html-to-text): lines wrapped at 78 characters, links followed by their URL, images and hidden elements (such as the MJML preview text) left out. **Locales**: the rendered locale is the first available among the requested one (`fr-CA`, compared case-insensitively), its base language (`fr`), the `defaultLocale`, then its base language. Otherwise, rendering fails. A template without translations takes the locales of its layout; without translations in both, the locale is ignored. **Data**: validated by the schema with `safeParseAsync` (async refinements work), and the parsed data is rendered. `mailer.render(template, { locale, data })` returns `{ template, locale, subject, html, text }`. `renderMail(template, { locale, defaultLocale, data })` does the same without a mailer. ## createMailer() | Option | Description | | --------------- | -------------------------------------------------------- | | `provider` | Required: the provider that sends. | | `from` | Required: the default sender. | | `replyTo` | Optional default reply-to addresses. | | `defaultLocale` | The locale used when the requested one is not available. | | `logger` | Optional: logs each sent message. | ### send() ```ts const { messageId } = await mailer.send(template, options) ``` | Option | Description | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `to` | Required: at least one address. | | `cc`, `bcc`, `replyTo` | Other recipients; `replyTo` replaces the default. | | `from` | Replaces the default sender. | | `subject` | Replaces the subject of the template. | | `locale` | The requested locale. | | `data` | The data, typed by the schema. | | `attachments` | `{ filename, content, contentType?, contentId? }`: `content` is a `Uint8Array` (a Node.js `Buffer` works) or a string; `contentId` makes it inline (``). Typed `MailAttachmentInput`; providers receive the validated `MailAttachment`. | | `headers` | Additional headers. `From`, `To`, `Subject`, `Content-Type` and the other headers set by the mailer are rejected. | | `tags`, `metadata` | See [Tags and metadata](#tags-and-metadata). | An address is `'ada@example.com'`, `'Ada Lovelace '` or `{ name, address }`, alone or in a list. Recipients, attachments, headers, tags and metadata are checked before rendering: an address without `@` or a line break in a name or a header throws a `MailMessageError`. `messageId` is the identifier given by the provider, if any. `mailer.sendMessage(options)` sends a message rendered elsewhere: the same options, with `subject`, and `html`, `text` or both. Without `text`, it is converted from `html`. ### Tags and metadata Tags group messages in the statistics of the provider; metadata comes back in its webhooks, to link a delivery, a bounce or a click to your app. - **Tags** and **metadata keys**: 1 to 256 letters, digits, `_` or `-`, the strictest rule among providers. Duplicate tags are removed. - **Metadata values**: strings on one line. | Provider | `tags` | `metadata` | | ---------------- | ---------------------------------- | --------------------- | | SendGrid | `categories` | `custom_args` | | Postmark | `Tag` (a single tag) | `Metadata` | | Brevo | `tags` | ignored | | Mailjet | ignored | `EventPayload` (JSON) | | Mailgun | `o:tag` | `v:` variables | | Scaleway | ignored | ignored | | Amazon SES | `EmailTags`, with the value `true` | `EmailTags` | | Resend | `tags`, with the value `true` | `tags` | | SMTP, nodemailer | ignored | ignored | | console, memory | printed, kept | printed, kept | A provider without tags or metadata ignores them: switching providers never breaks a call. ## Providers Every provider sends the sender, the reply-to addresses, several `to`, `cc` and `bcc`, the HTML and text versions, attachments (inline ones included) and additional headers, within the limits of its API. The providers based on an HTTP API (SendGrid, Postmark, Brevo, Mailjet, Mailgun, Scaleway) have no dependency, and accept `baseUrl` (region, proxy, tests) and `fetch` (replaces the global `fetch`); their errors are `MailSendError`, with the HTTP `status` and the message of the API. | Provider | Import | Settings | | -------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `createMemoryProvider()` | `@dotpress/mailer` | — | | `createConsoleProvider()` | `@dotpress/mailer` | `body` (prints the text version, off by default: messages contain secrets), `write` | | `createSmtpProvider()` | `@dotpress/mailer/smtp` | the [nodemailer](https://nodemailer.com/smtp/) options, or a URL (`smtps://user:password@smtp.example.com`); `pool: true` reuses connections, `close()` on shutdown | | `createNodemailerProvider(transporter, { name? })` | `@dotpress/mailer/smtp` | any nodemailer transporter (sendmail, stream…) | | `createSesProvider()` | `@dotpress/mailer/aws-ses` | `clientConfig` (region…), or `client`; `configurationSetName` | | `createResendProvider()` | `@dotpress/mailer/resend` | `apiKey` (else `RESEND_API_KEY`), or `client` | | `createSendgridProvider()` | `@dotpress/mailer/sendgrid` | `apiKey`; `baseUrl: 'https://api.eu.sendgrid.com'` for EU subusers | | `createPostmarkProvider()` | `@dotpress/mailer/postmark` | `serverToken` (`POSTMARK_API_TEST` for the test mode), `messageStream` (`outbound` by default) | | `createBrevoProvider()` | `@dotpress/mailer/brevo` | `apiKey` | | `createMailjetProvider()` | `@dotpress/mailer/mailjet` | `apiKey`, `apiSecret` | | `createMailgunProvider()` | `@dotpress/mailer/mailgun` | `apiKey` (or a sending key of the domain), `domain`; `baseUrl: 'https://api.eu.mailgun.net'` in the EU region | | `createScalewayProvider()` | `@dotpress/mailer/scaleway` | `secretKey`, `projectId`, `region` (`fr-par` by default) | - **Memory**: `outbox.sent` lists the messages, `last()` returns the last one, `clear()` empties it. - **SMTP**: nodemailer 10, Node.js only. Install `nodemailer`. SMTP errors (`cause.responseCode`, such as `550`) are `MailSendError`. - **Amazon SES**: the `SendEmail` operation of the API v2, with `@aws-sdk/client-sesv2` 3.782 or later. A message with inline attachments is built by the provider and sent as raw content, with its images next to the HTML version in a `multipart/related` part: with simple content, SES places them apart, and some clients, such as Thunderbird, show them at the end of the message instead of in the HTML. Credentials come from the environment. On AWS Lambda, the SDK of the Node.js runtime works, without bundling it, if its version is 3.782 or later. - **Resend**: install `resend`. - **SendGrid**: the message ID is read from the `X-Message-Id` response header, when present. - **Postmark**: the message ID is the `MessageID` of the response; errors include the Postmark `ErrorCode`. - **Brevo**: the message ID is the `messageId` of the response; errors include the Brevo `code`. - **Mailjet**: Mailjet returns an identifier per recipient: the message ID is the `MessageUUID` of the first `to` recipient (the numeric `MessageID` without UUID). A message rejected in a successful response is reported as an error too. - **Mailgun**: reply-to addresses and headers are sent as `h:` options. An inline attachment is sent with its `contentId` as file name, so `cid:` references work as with the other providers. The message ID is the `id` of the response. - **Scaleway**: the API has no reply-to field: it is sent as a `Reply-To` header. The message ID is the `id` of the email of the first recipient. ### Limits of the providers Checked before calling the API: a message over a limit throws a `MailMessageError`. | Provider | Limits | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SendGrid | 10 tags of 255 characters at most; metadata of 10,000 bytes at most (JSON); requests of 30 MB at most | | Amazon SES, Resend | metadata values of 1 to 256 letters, digits, `_` or `-` (identifiers, not email addresses or dates); a name cannot be both a tag and a metadata key | | Postmark | 50 recipients (`to`, `cc` and `bcc`); addresses of 254 characters and a sender of 255 at most; subjects of 2,000 characters at most; a single tag; no executable attachments (`.exe`, `.bat`, `.msi`…); requests of 10 MB at most | | Brevo | a single reply-to address; no inline attachments; names of 70 characters at most; the attachment extensions Brevo accepts (`pdf`, `png`, `docx`, `zip`…) | | Mailjet | a single reply-to address; requests of 15 MB at most | | Mailgun | 16 KB at most for the reply-to addresses, additional headers, tags and metadata together | | Scaleway | no inline attachments; subjects of 998 characters at most; no empty header values | Request sizes include the attachments, encoded in base64: a third larger than the files. ### Custom providers A provider has a `name` and a `send(message)` method, which returns `{ messageId }` or nothing. The message is normalized and frozen: `from`, `to`, `cc`, `bcc`, `replyTo` (each `{ name?, address }`), `subject`, `html` (undefined for a text-only message), `text`, `attachments`, `headers`, `tags`, `metadata`, and `template` and `locale` for the logs. `formatAddress()` formats an address for a header (`"Ada" `). Throw a `MailSendError` with the HTTP `status` of the API, and a `MailMessageError` for a message the provider cannot send. Other errors are wrapped in a `MailSendError`. ## mailerPlugin() ```ts import { mailerPlugin } from '@dotpress/mailer/plugin' await createApp({ adapter, plugins: [mailerPlugin(mailer)] }) ``` The plugin, named `mailer`, provides `ctx.mailer`: the mailer, logging with the request logger (`mailer.withContext({ logger })`). Using `ctx.mailer` without the plugin throws an explicit error. It has its own entry point: the main one does not depend on `@dotpress/core`. ## Logs With a `logger` (a Dotpress or Pino logger, or any object with `info`, `warn` and `error` methods, and optionally `debug`, taking `(data, message)`), each sent message is logged at the `info` level as `Mail sent`, with the provider, the template, the message ID and the number of recipients. Addresses are not logged. Failures are thrown, not logged. ## Performance MJML is loaded on the first render of an MJML template (about 100 to 300 ms), and html-to-text on the first text conversion. MJML compilation is cached by template and locale: later renders only run Mustache, in well under a millisecond. ## Errors | Error | When | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `TypeError` | Invalid options of `defineTemplate()`, `defineLayout()`, `createMailer()`, `send()`… | | `MailDataError` | The data does not match the schema. Fields: `template`, `issues`. | | `MailRenderError` | MJML missing or invalid, unknown translation key, no available locale, invalid Mustache, a failing source function. Fields: `template`, `cause`. | | `MailMessageError` | An invalid address, attachment, header, tag or metadata, or a limit of the provider. | | `MailSendError` | The provider failed. Fields: `provider`, `status`, `cause`. | The error classes extend `MailerError`. --- url: https://dotpress.dev/reference/cache.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Cache The options, stores and errors of `@dotpress/cache`. For a guide, see [Cache and memoization](https://dotpress.dev/services/cache.md). ## defineMemo() ```ts defineMemo({ name: 'user', load: (id: string) => db.users.findById(id) }) defineMemo({ name: 'author', batch: (ids: readonly string[]) => loadAuthors(ids), maxBatchSize: 100 }) ``` | Option | Description | | -------------- | ------------------------------------------------------------------------------------------------------ | | `name` | Used in errors and logs. | | `load` | Loads one value from its arguments. | | `batch` | Instead of `load`: loads the values of every key requested in the same tick, in one call. | | `key` | Optional: a string from the arguments, for arguments not compared by value (`key: (user) => user.id`). | | `maxBatchSize` | With `batch`: the maximum number of keys per call. | | `schedule` | With `batch`: when the batch runs, `setTimeout(run, 0)` by default. | - **Keys**: the arguments, compared by value: strings, numbers, booleans, `null`, `undefined`, bigints, dates, arrays and plain objects, whatever the order of their properties. - **Single flight**: calls made while a value loads share the load. A failed load fails the calls in progress, and is not kept: the next call loads again. - **Values** are the objects returned by `load`, not copies: a caller that mutates one changes it for the others. - **`batch`** receives the keys without duplicates, and returns a `Map` by key (missing keys give `undefined`), or an array in the order of the keys, where an `Error` fails its key only. An array of the wrong length fails every key with a `MemoBatchError`. Keys requested before the batch runs join it, awaits included; keys requested once it started go to the next one. ### The memo `createMemo()` creates a memo: one per request, event message or job, never one per process. | Call | Description | | ------------------------------------ | ----------------------------------------------- | | `memo(loader, ...args)` | The value, loaded once. | | `memo.set(loader, ...args, value)` | Replaces a value, after an update. | | `memo.delete(loader, ...args)` | The next call loads again. | | `memo.clear(loader)`, `memo.clear()` | Forgets the values of a loader, or every value. | ## defineCacheEntry() ```ts defineCacheEntry({ name: 'user', key: (id: string) => id, schema: z.object({ id: z.string(), name: z.string() }), ttl: '1h', tags: (id: string) => [`user:${id}`], }) ``` | Option | Default | Description | | --------------------------------------------------------------------------------- | ----------------------- | --------------------------------------------------------------------- | | `name` | required | Part of the key. | | `key` | the arguments | A string, a number, or a value compared like the arguments of a memo. | | `schema` | — | Validates every value read, and every value written. Types the value. | | `version` | `1` | Part of the key: increase it when the shape of the values changes. | | `tags` | — | A function of the arguments, returning the tags of the value. | | `ttl` | the `ttl` of the cache | How long a value is fresh. | | `grace`, `graceBackoff`, `staleWhileRevalidate`, `timeout`, `hardTimeout`, `lock` | the policy of the cache | See [Resilience](#resilience). | Keys are `prefix:name:vVersion:key`, like `app:user:v1:42`. Keys longer than the store accepts are hashed (SHA-256). Durations are a number of seconds, or a string: `'500ms'`, `'30s'`, `'10m'`, `'1h'`, `'7d'` (the `Duration` type of `@dotpress/core`, see [Options and durations](https://dotpress.dev/concepts/options.md#durations)). Without a `schema`, `getOrSet` returns the type of the loader, and `get` returns `unknown` (the `Untyped` value type of the entry): `defineCacheEntry<[id: string], User>({ … })` declares the type. ## createCache() | Option | Default | Description | | ------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `store` | required | See [Stores](#stores). | | `prefix` | — | Prefix of every key, like the name of the app. | | `ttl` | 1 hour | Default lifetime of the values. | | `grace`… `lock` | — | The default [resilience](#resilience) policy of the entries. | | `serializer` | JSON | `{ serialize, deserialize }`, such as superjson. | | `logger` | — | Logs store failures, stale values and events. | | `storeTimeout` | — | A slower store operation counts as a failure. Set it: a reconnecting client makes commands wait. | | `failOpen` | `true` | `false` throws a `CacheStoreError` when the store fails. | | `onError(error, { operation, key, entry })` | — | Every store failure; `operation` (`StoreOperation`) is `get`, `set`, `delete`, `invalidate`, `lock` or `unlock`. Its own errors are logged and ignored. | | `onAccess(access)` | — | Each result of `get` and `getOrSet`, for metrics. See [Accesses](#accesses). | | Method | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `getOrSet(entry, ...args, loader)` | The value, or loads, caches and returns it. Concurrent calls share the load. A failed load, or a load returning `undefined`, is not cached. | | `get(entry, ...args)` | A fresh value, or `undefined` when missing, expired or invalidated. | | `set(entry, ...args, value)` | Writes a value. | | `delete(entry, ...args)` | Removes a value for good. | | `invalidateTags(tags)` | Expires every value of these tags. | | `withContext({ logger })` | The same cache, with another logger: the logger of a request. `ctx.cache` is one. | ### Values Values are serialized with the `serializer`. `undefined` is not cached; `null` is. With a `schema`, a value read that no longer matches (written by an older version of the app) is a miss, not a crash. Values are checked when written too, as they will read back: JSON turns dates into strings, so `z.date()` fails and the value is not cached, with a warning, while `z.coerce.date()` works. `getOrSet` returns the value as it reads back: a hit and a miss return the same thing. The memory store serializes too, so that a caller cannot change a cached object. ### Resilience | Option | Default | Effect, once the `ttl` is over | | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `grace` | disabled | During this time, when the loader fails or times out, the expired value is returned instead of the error, with a `warn` log. | | `graceBackoff` | `'10s'` | After such a failure, the loader is not called again during this delay: the expired value is served directly. A successful load ends it. | | `staleWhileRevalidate` | disabled | During this time, the expired value is returned at once, and reloaded in the background, once per key. Failed refreshes are logged. | | `timeout` | none | With an expired value in its grace period, a slower load returns that value; the load goes on and caches its result. | | `hardTimeout` | none | A slower load fails with a `CacheTimeoutError`, or returns the expired value of the grace period. The load goes on and caches its result. | | `lock` | none | Distributed single flight, on stores with locks (Redis): one instance loads a missing value, under a lock held at most this long; the others read the value every 50 ms, and load it themselves if the lock was not released. Set it above the duration of the loader. | Values stay in the store for `ttl` plus the longer of `grace` and `staleWhileRevalidate`. Without a grace period, a failing loader fails the call. ### Tags Each tag has a random token in the store (`prefix:_tag:name`, kept 30 days or longer). A value records the tokens of its tags when written; `invalidateTags()` replaces them. Reading a value with tags reads their tokens too: one more round trip, grouped with `getMany` when the store has it. - A value whose token changed or vanished is expired: `get` returns `undefined`, and `getOrSet` reloads it. With a `grace` period, it can still be served when the loader fails, never by `staleWhileRevalidate`: the data changed. - When the tokens cannot be read, values with tags count as invalidated, and new values are not cached. ### Accesses `onAccess(access)` receives a `CacheAccess`, `{ type, reason?, entry, key }`: `type` is `hit`, `miss` or `stale`, and `reason` (for a stale value) is `revalidate`, `error`, `timeout` or `backoff`. The same accesses are logged at the `debug` level. ### Store failures By default, the cache fails open: a failed read is a miss (the loader runs), a failed write is skipped. Every failure is logged, `warn` for reads and writes, `error` for deletions and invalidations (they may leave outdated values), and passed to `onError`. ## Stores | Store | Import | Use | | ------------------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `createMemoryStore({ maxEntries })` | `@dotpress/cache` | The memory of the process: one instance, development, tests. The least recently used entries are removed beyond `maxEntries` (10,000 by default). | | `createRedisStore({ client })` | `@dotpress/cache/redis` | Redis or Valkey, with a node-redis or ioredis client. | | `createUpstashStore({ url, token })` | `@dotpress/cache/upstash` | Upstash Redis over its REST API: every runtime, edge included. | | `createCloudflareKvStore({ kv })` | `@dotpress/cache/cloudflare-kv` | Workers KV, from a Worker. | ### Redis and Valkey ```ts import { createClient } from 'redis' // or: import { Redis } from 'ioredis' import { createRedisStore } from '@dotpress/cache/redis' const client = createClient({ url: process.env.REDIS_URL }) client.on('error', (error) => logger.error({ error }, 'Redis error')) await client.connect() const cache = createCache({ store: createRedisStore({ client }), prefix: 'app', storeTimeout: '200ms' }) // On shutdown: await client.close() (node-redis 5 or later; quit() with node-redis 4 and ioredis) ``` - The store uses the client of the app, which connects and closes it: [node-redis](https://github.com/redis/node-redis) (`redis`, v4 or later) or [ioredis](https://github.com/redis/ioredis). - It works with Redis, Valkey, managed services (ElastiCache, Memorystore…) and servers of the same protocol (Dragonfly, KeyDB…). - Commands: `GET`, `MGET` (tags), `SET … PX`, `DEL`, and for `lock`, `SET … NX PX` and a Lua script that releases a lock with its token only. - Cluster clients (`createCluster()`, `new Cluster()`) are refused for now: use a standalone server, or the primary of a replicated one. - A Redis used as a cache only can evict the least recently used keys (`maxmemory-policy allkeys-lru`); a Redis shared with BullMQ needs `noeviction`. ### Upstash ```ts import { createUpstashStore } from '@dotpress/cache/upstash' const store = createUpstashStore({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN, // the standard token: the read-only one cannot write }) const cache = createCache({ store, prefix: 'app', storeTimeout: '500ms' }) ``` The store calls the [REST API](https://upstash.com/docs/redis/features/restapi) of Upstash Redis with `fetch`: no dependency, no connection to open or close. It runs on Cloudflare Workers, Vercel, Deno, Bun and Node.js. Each operation is one HTTPS request. Errors of the API (`401`, `400 ERR …`) are store failures. A request is limited to 10 MB on the free and pay-as-you-go plans. The `fetch` option replaces the global `fetch`. The `@upstash/redis` SDK is not needed: by default, it applies `JSON.parse` to every reply, which would change the cached values. ### Cloudflare Workers KV ```jsonc // wrangler.jsonc { "kv_namespaces": [{ "binding": "CACHE", "id": "" }] } ``` ```ts import { env } from 'cloudflare:workers' import { createCloudflareKvStore } from '@dotpress/cache/cloudflare-kv' const cache = createCache({ store: createCloudflareKvStore({ kv: () => env.CACHE }), prefix: 'app' }) ``` `kv` is the binding, or a function that returns it. [Workers KV](https://developers.cloudflare.com/kv) suits values read often and changed rarely: configuration, catalogs, rendered pages. | Limit | Effect | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | Eventual consistency | A write, deletion or invalidation can take 60 seconds or more to reach other locations, which serve the previous value meanwhile. | | Expiration of 60 seconds at least | Shorter `ttl` are kept in the value: the cache expires them on time, KV removes them after 60 seconds. | | One write per second per key | Faster writes fail with a `429`: a store failure. `invalidateTags()` writes a token per tag. | | Keys of 512 bytes | Longer keys are hashed. | | No locks | The `lock` option is ignored. | | Free plan: 1,000 writes per day | Cache misses write: count them before choosing KV. | `cacheTtl` (30 seconds at least) keeps the values read in the cache of the location for longer: faster reads, but changes are seen even later. The tokens of tags are read in bulk, 100 keys per read. ### Custom stores A store implements `CacheStore`: `name`, `get(key)`, `set(key, value, ttl)` (strings, `ttl` in milliseconds) and `delete(key)`, and optionally `getMany(keys)` (one round trip for the tokens of tags), `lock(key, ttl)` and `unlock(key, token)` (the `lock` option), and `maxKeyLength` (in bytes). ## cachePlugin() ```ts import { cachePlugin } from '@dotpress/cache/plugin' await createApp({ adapter, plugins: [cachePlugin({ cache, memoScope: asyncLocalMemo })] }) ``` | Option | Description | | ----------- | -------------------------------------------------------------------------------------------------------- | | `cache` | Optional: provides `ctx.cache`, the cache with the request logger. Without it, using `ctx.cache` throws. | | `memoScope` | Optional: `asyncLocalMemo` runs each request in the scope of its memo. | The plugin, named `cache`, provides `ctx.memo`: a new memo for each request, created on first use. ### @dotpress/cache/als With [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html): Node.js, Bun, Deno, and Cloudflare Workers with the `nodejs_compat` flag. | Export | Description | | ------------------ | ------------------------------------------------------------------- | | `asyncLocalMemo` | The `memoScope` of the plugin. | | `memoized(loader)` | A function that reads the memo of the current scope. | | `runWithMemo(fn)` | Runs `fn` in the scope of a new memo: one per event message or job. | | `currentMemo()` | The memo of the scope, for `set` and `delete`. | Outside a scope, `currentMemo()` and the `memoized()` functions throw an explicit error: there is no global memo. ## Errors | Error | When | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `TypeError` | Invalid options and arguments; the message names the option. | | `MemoBatchError` | `batch` returned values that do not match the keys. Field: `memo`. | | `CacheTimeoutError` | A load exceeded `hardTimeout`, without a stale value to serve. Fields: `entry`, `key`, `timeout`. | | `CacheStoreError` | The store failed or timed out, with `failOpen: false`. Fields: `store`, `operation`, `key`, `cause`. Also passed to `onError`. | The error classes extend `CacheError`. --- url: https://dotpress.dev/reference/openapi.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # OpenAPI The functions, options and command of `@dotpress/openapi`. For a guide, see [OpenAPI and API docs](https://dotpress.dev/services/openapi.md). ## openapiPlugin() ```ts import { openapiPlugin } from '@dotpress/openapi' const docs = openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0' } }) await createApp({ adapter, plugins: [docs] }) ``` Serves the document of the app, and an API reference page (Scalar). Unknown options are rejected. | Option | Default | Description | | ----------------- | ------------------------------- | --------------------------------------------------------------------------------------------- | | `info` | required | `title` and `version`, and the other fields of the OpenAPI `info` object. | | `servers` | the public base path of the app | The servers of the document. | | `tags` | — | Descriptions of the tags used by the routes (`meta.tags`). | | `externalDocs` | — | A link to external documentation. | | `securitySchemes` | — | Security schemes, added to those of the plugins (`AUTH_SECURITY_SCHEMES` of the auth plugin). | | `path` | `'/openapi.json'` | The path of the document. | | `ui` | `{ path: '/docs' }` | The API reference page, or `false` to serve the document only. | | `middlewares` | `[]` | Middlewares of the document and page routes, for instance `requireRole('admin')`. | | `ui` option | Default | Description | | ----------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `path` | `'/docs'` | The path of the page. | | `title` | `info.title` | The title of the page. | | `configuration` | `SCALAR_NEUTRAL_CONFIGURATION` | The [Scalar configuration](https://guides.scalar.com/scalar/scalar-api-references/configuration), merged with the neutral one. | | `cdnUrl`, `integrity` | a pinned version on jsDelivr, with its hash | The script of Scalar, to host it yourself. | | `contentSecurityPolicy` | the policy of the page | Extra sources for the directives of the Content Security Policy of the page (`{ 'img-src': ['https://cdn.example.com'] }`), or `false` for no policy. The page allows the Scalar script, its inline script by hash, and requests to the document and its `servers`. See [Content Security Policy](https://dotpress.dev/services/openapi.md#content-security-policy). | `docs.getDocument()` returns the document, once the app is created. The warnings of the generation (a scheme used but not declared, a schema without JSON representation) are logged by the plugin. ## generateOpenApi() ```ts import { generateOpenApi } from '@dotpress/openapi' const document = generateOpenApi(app, { info: { title: 'Tasks API', version: '1.0.0' } }) ``` Returns the document of an app, or of a list of `RouteInfo` (`app.routes`). It takes the options of the plugin, except `path`, `ui` and `middlewares`, plus `onWarning(message)` (`console.warn` by default). ## dotpress-openapi ```sh npx dotpress-openapi src/server.ts --out openapi.json ``` | Argument | Description | | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `` | The module that creates the app, like the entry point of the server or of AWS Lambda; or a module exporting the app, or a function creating it. | | `--export ` | The export to use, when the module does not create one app. Defaults to `default`, or to the only exported app or function. | | `--out ` | Writes the document to a file, instead of the standard output. | | `--title`, `--api-version` | `info` of the document, without `openapiPlugin()`. Default to the name and version of the `package.json` of the current directory. | | `--help`, `-h` | Prints the usage. | The module runs without starting a server: `app.listen()` opens no port, the factory of `createLambdaHandler()` is called right away, and what the module prints goes to the standard error. An exported function receives an adapter that mounts nothing, as its single argument (`createApp(adapter)` or `createApp({ adapter })`). With `openapiPlugin()` in the app, its document is used as is. The apps are closed afterwards, and the command exits with a non-zero code on failure. ## Types `OpenApiDocument` and the types of its objects (`InfoObject`, `OperationObject`, `JsonSchema`…) describe the subset of OpenAPI 3.1 that Dotpress writes. They may gain optional fields in minor versions. `OpenApiSource` is what `generateOpenApi()` accepts: an app, or a list of `RouteInfo`. --- url: https://dotpress.dev/reference/testing.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Testing The helpers of `@dotpress/testing`, built on [Vitest](https://vitest.dev). For guides, see [Testing](https://dotpress.dev/routing/testing.md) and [Testing helpers](https://dotpress.dev/services/testing.md). ```sh npm install -D @dotpress/testing vitest ``` ## createTestApp() ```ts import { createTestApp } from '@dotpress/testing' const { fetch, logger, close } = await createTestApp({ routers: [tasksRouter], plugins: [authPlugin(auth)] }) const res = await fetch('/tasks', { headers: { authorization: `Bearer ${token}` } }) ``` Creates an app on the memory adapter. It takes the options of `createApp()`, except `adapter`, which takes the options of the memory adapter, and `logger`, a memory logger (a new one by default). | Member | Description | | -------------------- | -------------------------------------------------------------------------- | | `fetch(path, init?)` | Sends a request, like `fetch()`: `path` is relative to `http://localhost`. | | `app` | The app. | | `adapter` | The memory adapter. | | `logger` | The memory logger of the app. | | `close()` | Closes the app. | ## memoryAdapter() The adapter of `createTestApp()`, for an app created by your own code: `createTasksApp({ adapter: memoryAdapter() })`. Its `fetch(request)` takes a Web `Request`. | Option | Default | Description | | ----------- | ------------- | -------------------------------------- | | `bodyLimit` | 1 MiB | Maximum body size, in bytes. | | `ip` | `'127.0.0.1'` | The client IP address of the requests. | ## createMemoryLogger() A logger that records its lines in `entries` (`{ level, args }`) instead of printing them. ## Assertions | Function | Description | | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `expectEventEmitted(source, event, payload?, { times?, metadata?, delay? })` | An event was emitted, with a payload matching partially. Returns the last matching emission. | | `expectEventNotEmitted(source, event, payload?)` | No such event was emitted. | | `expectMailSent(outbox, criteria?, { times? })` | A message was sent, matching the criteria. Returns the last matching one. | | `expectNoMailSent(outbox, criteria?)` | No such message was sent. | The source of events is a fake event bus (`createFakeEventBus()`) or a memory transport; the outbox is the memory provider of the mailer. A failed assertion throws an `ExpectationError` that lists what was emitted or sent. | Mail criterion | Matches | | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `to`, `cc`, `bcc`, `replyTo` | An address, or a list (`ExpectedAddresses`), all among the recipients. | | `from` | The sender. | | `template` | The template, or its name. | | `subject`, `html`, `text`, `locale`, `tags`, `metadata`, `headers`, `attachments` | Like `toMatchObject()`, with asymmetric matchers. | ## AWS Lambda | Function | Description | | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `createLambdaTarget(handler, { format, close?, sourceIp? })` | A `TestTarget` that sends each request to a Lambda handler as an event of the format (`'v1'`, `'v2'`, `'alb'`, or `'alb-single-value'` for a load balancer without multi-value headers). A failed invocation gets a `502`. | | `toLambdaEvent(request, format, sourceIp?)` | The event of a Web `Request`. | | `fromLambdaResult(result, format?)` | The Web `Response` of a result. With `'alb-single-value'`, only `headers` are read, like the load balancer. | ## @dotpress/testing/conformance The conformance suite of the adapters: see [Writing an adapter](https://dotpress.dev/services/testing.md#writing-an-adapter). | Export | Description | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `runConformanceSuite({ name, setup, bufferedResponses? })` | Registers the tests of the suite. `setup(options)` creates an app with the adapter under test and the given options, and returns a `TestTarget`. `bufferedResponses` skips the scenarios that need incremental streaming. | | `createHttpTarget(baseUrl, { close? })` | A target for a server listening on a port. | | `createFetchTarget(handle, { close? })` | A target for a function taking a Web `Request` and returning a `Response`. | A `TestTarget` has `fetch(path, init?)` and `close()`, which does nothing by default. --- url: https://dotpress.dev/reference/adapters.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Adapters The adapters of `@dotpress/adapter-express`, `@dotpress/adapter-fastify` and `@dotpress/adapter-hono`, and their AWS Lambda handlers. For a guide, see [Adapters](https://dotpress.dev/adapters/index.md). ## Options Every adapter takes the same options, and rejects unknown ones: | Option | Default | Description | | ------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `app` | a new application | The Express, Fastify or Hono application to mount the routes on, with its own settings. | | `beforeRoutes(app)` | — | Registers native middlewares, hooks and routes before the Dotpress routes. | | `afterRoutes(app)` | — | Registers native middlewares and routes after them. With Fastify, in an encapsulated context: they do not apply to the Dotpress routes. | | `bodyLimit` | `1048576` (1 MiB) | Maximum body size, in bytes. A route overrides it with its own `bodyLimit`. | | `getIp(c)` | the address of the connection | Hono only: the IP address of a request, for instance from a header set by your proxy. | The option types take the application as a parameter, with a default: `ExpressAdapterOptions` is `ExpressAdapterOptions`, `FastifyAdapterOptions` is `FastifyAdapterOptions`, `HonoAdapterOptions` is `HonoAdapterOptions`. ## expressAdapter() ```ts import { expressAdapter } from '@dotpress/adapter-express' const adapter = expressAdapter({ bodyLimit: 5 * 1024 * 1024 }) ``` | Member | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `native()` | The Express application, also `app.native()`. | | `listen(port, host?)` | Starts an HTTP server, and returns `{ port, host }`. Refuses a second call. | | `close()` | Stops the server started by `listen()`, after the pending requests, and closes the responses being streamed, also when the app serves the Express application with its own server. | | `server()` | The HTTP server started by `listen()`, or `undefined`. | Express 4 and 5 are supported. `@types/express` types `native()`: without it, the application is `any`. See [Express](https://dotpress.dev/adapters/express.md). ## fastifyAdapter() ```ts import { fastifyAdapter } from '@dotpress/adapter-fastify' const adapter = fastifyAdapter({ app: Fastify({ trustProxy: true }) }) ``` | Member | Description | | --------------------- | --------------------------------------------------------------------------------------------------------------------- | | `native()` | The Fastify instance. | | `listen(port, host?)` | Starts the server (`::`, or `0.0.0.0` without IPv6, by default), and returns `{ port, host }`. Refuses a second call. | | `close()` | Closes the responses being streamed, then the Fastify instance. | | `server()` | The HTTP server, once listening. | See [Fastify](https://dotpress.dev/adapters/fastify.md). ## honoAdapter() ```ts import { honoAdapter } from '@dotpress/adapter-hono' // fetch: Bun, Deno, Workers… import { honoAdapter } from '@dotpress/adapter-hono/node' // Node.js server ``` | Member | Entry | Description | | ----------------------------------------- | ------- | --------------------------------------------------------------------------------------------------- | | `native()` | both | The Hono application. | | `fetch(request, env?, executionContext?)` | both | Handles a Web `Request`. | | `close()` | both | Closes the responses being streamed. | | `listen(port, host?)` | `/node` | Starts a Node.js server (`@hono/node-server`), and returns `{ port, host }`. Refuses a second call. | | `server()` | `/node` | The Node.js server, once listening. | See [Hono](https://dotpress.dev/adapters/hono.md). ## createLambdaHandler() ```ts import { createLambdaHandler } from '@dotpress/adapter-hono/lambda' // or '@dotpress/adapter-fastify/lambda' export const handler = createLambdaHandler(() => createApp({ adapter: honoAdapter() })) ``` Both entries export the same function and types. The factory creates the app at the first invocation; its failures are logged, answered with a `500`, and retried at the next invocation. | Option | Default | Description | | ---------------------------------- | --------------------------------- | ------------------------------------- | | `logger` | a console logger | Logs the failures to create the app. | | `isContentTypeBinary(contentType)` | everything but text, JSON and XML | Whether a response is sent in base64. | | Type | Description | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LambdaEvent` | An event of API Gateway (payload v1 or v2), a Function URL or an Application Load Balancer: the types of `@types/aws-lambda` fit. | | `LambdaContext` | The context of the invocation. | | `LambdaResult` | The result, in the format of the event: `statusCode`, `headers`, `multiValueHeaders`, `cookies`, `body`, `isBase64Encoded`, and `statusDescription` for load balancers. | | `LambdaHandler` | `(event, context?) => Promise`. | | `LambdaApp` | What the factory returns: an app created with the adapter of the entry. | See [AWS Lambda](https://dotpress.dev/adapters/aws-lambda.md). ## Writing an adapter An adapter implements `HttpAdapter` of `@dotpress/core`, with the functions of `@dotpress/core/adapter`: see [For adapter authors](https://dotpress.dev/reference/application.md#for-adapter-authors). The [conformance suite](https://dotpress.dev/services/testing.md#writing-an-adapter) checks it. --- url: https://dotpress.dev/reference/migrate-from-v1.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Migrate from v1 Dotpress 2 is a rewrite. The style of the API stays (`defineRoute()`, `createRouteGroup()`, handlers that return their value), but the framework is no longer built on Express, and there is no compatibility layer. This page lists every change that requires action, in the order of a migration. :::tip How to migrate Migrate the app first ([Runtime](#runtime) to [Plugins](#plugins)), with your tests. Then migrate the authentication: its changes reach the clients, the database and the sessions of your users, see [What your users will notice](#what-your-users-will-notice). ::: ## Runtime - **Node.js 22.12 or later.** Every package declares `"engines": { "node": ">=22.12" }`. - **ES modules only.** No CommonJS build: CommonJS projects load the packages with `require()`, which Node.js 22.12 supports for ES modules. - **Zod 4.** Zod 3 is no longer supported. Zod 4 changes some error codes, messages and APIs: see the [Zod 4 changelog](https://zod.dev/v4/changelog). ## Packages The `dotpress` package is replaced by `@dotpress/core` and an [adapter](https://dotpress.dev/adapters/index.md): ```ts // v1 import { createApp, defineRoute } from 'dotpress' // v2 import { createApp, defineRoute } from '@dotpress/core' import { expressAdapter } from '@dotpress/adapter-express' ``` Express is no longer a dependency of the core. To keep it, install `@dotpress/adapter-express`, which supports Express 4 and 5. You can also move to Fastify, Hono or AWS Lambda without changing your routes. ## Application ### createApp() takes an adapter `createApp()` returns a Dotpress app, no longer an Express application: ```ts // v1 const app = await createApp() app.listen(3000) // v2 const app = await createApp({ adapter: expressAdapter() }) await app.listen(3000) ``` The Express application is `app.native()`. Call `app.close()` on `SIGTERM`, for a [graceful shutdown](https://dotpress.dev/deployment/node.md#graceful-shutdown). ### Options | v1 | v2 | | ---------------------------------------- | -------------------------------------------------------------------------------------------------- | | `useBeforeRoutes: (app) => …` | `expressAdapter({ beforeRoutes: (app) => … })` | | `useAfterRoutes: (app) => …` | `expressAdapter({ afterRoutes: (app) => … })` | | `isDev` | `exposeErrors: true`. Dotpress never reads `process.env`. | | `onException: (err, req) => …` | `onError: (error, ctx) => …`, for every unexpected error | | `cors: { disable }` | `cors: { origin, credentials }`. Disabled without it. | | `enableHttpLogging`, `onRequestComplete` | The [`onResponse` hook](https://dotpress.dev/routing/logging.md#logging-every-request) of a plugin | | Pino, loaded when installed | `logger: pino()`, passed explicitly. The default logger uses `console`. | ```ts // v1 await createApp({ useBeforeRoutes: (app) => app.use(helmet()), onException: (err) => Sentry.captureException(err), }) // v2 await createApp({ adapter: expressAdapter({ beforeRoutes: (app) => app.use(helmet()) }), onError: (error) => Sentry.captureException(error), }) ``` Errors of Dotpress routes never reach the Express error handlers: report them with `onError`. Errors passed to `next(error)` by native middlewares are converted to the Dotpress error format. ### CORS v1 enabled CORS by default, without an `Access-Control-Allow-Origin` header. In v2, CORS is disabled until you list the allowed origins: ```ts await createApp({ adapter, cors: { origin: ['https://app.example.com'], credentials: true } }) ``` Preflight responses list the methods of the path. An `OPTIONS` request that is not a preflight from an allowed origin gets `405` (or `404`), unless you define an `OPTIONS` route. See [CORS](https://dotpress.dev/routing/http-options.md#cors). ## Routes ### Path parameters come from the path The `params: ['id']` form is removed: parameters are typed from the path, group prefixes included. ```ts // v1 defineRoute({ path: '/orgs/:orgId/members/:id', schema: () => ({ params: ['orgId', 'id'] }), handler: async ({ req }) => req.params.id, }) // v2: req.params is { orgId: string; id: string } defineRoute({ path: '/orgs/:orgId/members/:id', handler: async ({ req }) => req.params.id, }) ``` A Zod schema can still validate or transform them: `schema: (z) => ({ params: z.object({ id: z.coerce.number() }) })`. ### Paths and matching - **Only static and `:param` segments.** Wildcards, optional parameters and regular expressions are rejected at startup. Paths and prefixes start with `/`. - **Case-sensitive**: Express was not, by default. - **Static segments win**, whatever the declaration order: `/users/me` over `/users/:id`. - **Conflicts are rejected**: two routes with the same method and path make `createApp()` throw. - Express settings (`case sensitive routing`, `strict routing`, `query parser`) do not apply to Dotpress routes. See [Paths](https://dotpress.dev/routing/routes.md#paths). ### Routers replace the test helpers | v1 | v2 | | ------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `$clearRoutes()`, `$clearResponseFilters()` | `globalRouter.clear()`, or better, an explicit router per test | | `getAllRoutes()` | `app.routes` | | `getResponseFilters()` | — (the filters are passed to `createApp()`, a router or a plugin) | | Response filters, global | `createApp({ responseFilters })`, `router.addResponseFilter()`, or the global `addResponseFilter()` | `defineRoute()` and `createRouteGroup()` still register on a global router, mounted when `createApp()` has no `routers`. `createRouter()` creates explicit routers: see [Routers](https://dotpress.dev/routing/routes.md#routers). ## Handlers ### ctx.req and ctx.res are no longer Express objects They are the same on every adapter: - `ctx.req`: `method`, `path`, `url`, typed `params`, `query`, `body` and `files`, `headers` (lowercase names), `cookies`, `ip`, `signal`, `header(name)`; - `ctx.res`: `setStatus()`, `setHeader()`, `appendHeader()`, `removeHeader()`, `setCookie()`, `clearCookie()`. The native request is `ctx.raw`, as an escape hatch. `cookie-parser` is no longer needed: `ctx.req.cookies` is always there. See [Request context](https://dotpress.dev/reference/context.md). ### Handlers return the response A handler can no longer write the response itself: ```ts // v1 handler: async ({ res }) => { res.status(201).json({ id }) } // v2 handler: async ({ res }) => { res.setStatus(201) // or `status: 201` on the route return { id } } ``` | v1 | v2 | | ---------------------------------- | ----------------------------------------------------------------------- | | `res.json(data)` | `return data`, or `return json(data, { status, headers })` | | `res.send('OK')` | `return text('OK')` | | `res.redirect('/login')` | `return redirect('/login')` | | `res.download()`, `res.sendFile()` | `return file(bytes, { filename, contentType })` | | `res.write()` | `return stream(source)`, or `return sse(source)` for Server-Sent Events | | `res.status(204).end()` | `return` nothing, or `return empty()` | **Returning nothing always responds `204`.** In v1, it did only with a `z.never()` response schema, and sent no response otherwise. See [Responses](https://dotpress.dev/routing/responses.md). `ctx.req.signal` is aborted when the client disconnects: pass it to long work, and streams stop with it. ## Middlewares ### They run before validation v1 validated the request, then ran the middlewares. v2 runs the middlewares first: 1. middlewares: plugins, app, groups, route; 2. request validation; 3. the handler; 4. response validation, then the response filters. Two consequences: - an anonymous request with an invalid body now gets the `401` of the authentication middleware, not a `400`; - middlewares see the raw `params`, `query` and `body`. Only handlers see the parsed values. ### Their return value is checked A middleware returns nothing to continue, or an `HttpError` or a response helper (`redirect()`…) to stop the request. Any other value is a bug, and gives a `500`. ## Errors ### One format Every error, `404` and `500` included, has the same body. Clients that read the `code` key of the v1 framework errors must read `error`: ```json { "status": 404, "error": "NOT_FOUND", "message": "Route not found" } ``` | Request | v1 | v2 | | ------------------------- | --------------------------------------- | ------------------------------------------------ | | No route | `404`, `code` key, `No matching route.` | `404 NOT_FOUND`, `Route not found` | | Path exists, other method | `404` | `405 METHOD_NOT_ALLOWED`, with an `Allow` header | | Invalid JSON body | `500` | `400 MALFORMED_BODY` | | `throw notFoundError()` | `500 INTERNAL_ERROR` | `404`, like `return notFoundError()` | | Body too large | beyond 100 KB | `413 PAYLOAD_TOO_LARGE`, beyond 1 MiB | | Compressed body | — | `415 UNSUPPORTED_MEDIA_TYPE` | The error helpers and `new HttpError()` take the details of the body in an options object, with the original error: `notFoundError('Task not found', { data: { id }, cause })`. See [Responses and errors](https://dotpress.dev/reference/responses.md#errors-produced-by-dotpress). ### Validation errors The issues are a flat list, each with its source: ```json // v1 { "error": "Validation failed", "details": [{ "source": "body", "issues": [{ "path": ["name"], "code": "invalid_type", "message": "…" }] }] } // v2 { "status": 400, "error": "VALIDATION_FAILED", "message": "Validation failed", "data": { "issues": [{ "source": "body", "path": ["name"], "code": "invalid_type", "message": "…" }] } } ``` Codes and messages come from Zod 4, unchanged. ## Request bodies v1 parsed JSON only, with the defaults of `express.json()`. Every adapter of v2 parses bodies the same way: | Content type | `req.body` | | ----------------------------------- | ------------------------------------- | | `application/json`, `*+json` | the parsed JSON | | `application/x-www-form-urlencoded` | strings, repeated keys giving arrays | | `multipart/form-data` | the text fields, files in `req.files` | | `text/*` | a string | | anything else | a `Uint8Array` | | no body | `undefined` (v1: `{}`) | - **The limit is 1 MiB** (v1: 100 KB): `bodyLimit` on the adapter, or on a route. - **The query string is parsed like a form**: `a[b]=1` is no longer expanded into objects. - **Webhook signatures**: `rawBody: true` on the route gives `req.rawBody`, without a custom `express.json({ verify })`. ## File uploads Multer is no longer used. Files are validated by a `files` schema, and received as Web `File` objects: ```ts // v1 defineRoute({ method: 'post', path: '/avatar', files: { avatar: { maxSize: 2_000_000, mimeTypes: ['image/png'], extensions: ['.png'] } }, handler: async ({ getFile }) => { const avatar = getFile('avatar') // MulterFile | undefined }, }) // v2 defineRoute({ method: 'post', path: '/avatar', bodyLimit: 3_000_000, schema: (z) => ({ files: z.object({ avatar: z .file() .max(2_000_000) .mime(['image/png']) .refine((file) => file.name.endsWith('.png'), 'Invalid extension'), }), }), handler: async ({ req }) => { const bytes = new Uint8Array(await req.files.avatar.arrayBuffer()) }, }) ``` - Invalid files give the usual `400 VALIDATION_FAILED`, with `source: 'files'` issues. - Uploads count in the body limit: raise `bodyLimit` on upload routes. - A repeated field gives an array of files: `arrayOf()` always gives an array. - Files are kept in memory, as with the `memoryStorage` of v1. See [File uploads](https://dotpress.dev/routing/bodies.md#file-uploads). ## Plugins Plugins are objects, declared with `definePlugin()`: ```ts // v1 const myPlugin: Plugin = (api) => { api.addRoute({ … }) } // v2 const myPlugin = definePlugin({ name: 'my-plugin', dependsOn: ['auth'], // optional async setup(api) { api.defineRoute({ … }) }, }) ``` | v1 | v2 | | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `api.addRoute()` | `api.defineRoute()` | | `api.addGroup()` | `api.createGroup()` | | `api.useBeforeRoutes()`, `api.useAfterRoutes()` | Removed: a plugin does not depend on an adapter | | Registration at any time | During `setup()` only | | — | `decorateContext()`, `onError()`, `hooks` (`onInit`, `onReady`, `onRequest`, `wrapRequest`, `onResponse`, `onClose`), `getRoutes()`, `getPlugin()`, `logger` | Plugin names are unique; missing or circular dependencies make `createApp()` throw. See [Plugin API](https://dotpress.dev/reference/plugins.md). ## Typing `AppTypes` is replaced by module augmentation. The user type is declared on `AuthUser`, and other keys on `RequestContext`: ```ts // v1 declare module 'dotpress' { interface AppTypes { user: User } } // v2 declare module '@dotpress/auth' { interface AuthUser { id: string roles: string[] } } ``` The augmentation of the Express `Request` (`id`, `files`, `user`) is removed: use `ctx.requestId`, `ctx.req.files` and `ctx.user`. See [Typing](https://dotpress.dev/concepts/typing.md). ## Authentication ### The service and the plugin `configurePlugin(settings)` is replaced by a service, `createAuth(settings)`, given to the app with `authPlugin(auth)`. The service also works without an app, in scripts and workers. ```ts // v1 const app = await createApp({ plugins: [configurePlugin({ keys, dataProvider })] }) // v2 const auth = createAuth({ keys, dataProvider, issuer: 'https://api.example.com' }) const app = await createApp({ adapter: expressAdapter(), plugins: [authPlugin(auth)] }) ``` | v1 | v2 | | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `generateTokensForUser()`… | Methods of the service, asynchronous: `await auth.generateTokensForUser({ userId })` | | `generateAccessToken()` | Removed: a token without session could not be revoked. `generateTokensForUser()` issues a token pair in a new session. | | `revokeTokens(userId)` of your data provider, to log a user out everywhere | `await auth.revokeUserSessions(userId)` | | `setAuthCookies(res, tokens)`, `clearAuthCookies(res)` | `auth.setAuthCookies(ctx.res, tokens)`, `auth.clearAuthCookies(ctx.res)` | | `req.user` | `ctx.user`, and the token in `ctx.auth` | | — | `requireAuth`, `requireRole(...roles)`, `requireClient(...clientIds)` | | `refreshTokenTTLInDays: 14` | `session: { idleTimeout: '14d' }`, and `session.absoluteTimeout` | | `aud` setting, login field `aud` or `client` | `clients: { allowed, required?, isUserRoleAllowed? }`, login field `clientId` | | The routes under `/auth` | Unchanged; `authPlugin(auth, { prefix })` to move them, `{ routes: false }` to remove them | ### Settings to change - **`issuer` is required**, and the `iss` claim is checked: one value per environment and application, such as the URL of the API. - **`keys.secretKey` is renamed `keys.privateKey`.** - **Unknown settings are rejected**: a misspelled setting throws at startup instead of being ignored. The setting types are named `AuthOptions`, `AuthCookieOptions`, `SessionOptions`… - **Keys in PKCS#8 and SPKI.** PKCS#1 keys (`BEGIN RSA PRIVATE KEY`) make `createApp()` fail. Converting a key does not change it: existing tokens stay valid. ```sh openssl pkcs8 -topk8 -nocrypt -in private.pem -out private.pkcs8.pem openssl rsa -RSAPublicKey_in -in public.pem -pubout -out public.spki.pem ``` - **Only RS256** is accepted. - **The `secure` flag of cookies is `true` by default** (v1: only when `NODE_ENV` is `production`). Chrome and Firefox accept secure cookies on `http://localhost`; Safari needs HTTPS, or `secure: false` in development. - **In cookie mode, list the origins of your app** if it is not served from the API origin: in the `cors` option with `credentials: true`, or in `cookies.trustedOrigins`. Cross-site requests from other origins are no longer authenticated by the cookie. See [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md#protection-against-cross-site-request-forgery). ### The data provider | Method | Change | | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `storeRefreshToken(payload)` | The payload has a `sessionId`, to store. `jwtId` is renamed `accessTokenId`. The token itself is not given: store its `tokenHash`. | | `findRefreshToken(tokenHash)` | Returns `accessTokenId` (v1 `jwtId`), and the stored `sessionId` and `usedAt`. | | `markRefreshTokenAsUsed(tokenHash, usedAt)` | New `usedAt` parameter, to store. | | `revokeTokens(userId)` | Renamed `revokeUserTokens(userId)`. | | `revokeSessionTokens(sessionId)` | New, required: revokes every refresh token of a session. | | `findUserById(id)` | Returns an `AuthUser`, and `undefined` for deleted, disabled or banned accounts: their sessions are no longer refreshed. | | `isSessionRevoked(sessionId)` | New, optional: rejects the access tokens of a revoked session at once. | | `updatePasswordHash(userId, hash)` | New, optional: upgrades the hashes of another cost at login. | For an SQL table: ```sql ALTER TABLE refresh_tokens ADD COLUMN session_id VARCHAR(36) NULL; ALTER TABLE refresh_tokens ADD COLUMN used_at TIMESTAMP NULL; -- the type of expires_at: TIMESTAMPTZ on PostgreSQL CREATE INDEX refresh_tokens_session_id ON refresh_tokens (session_id); ``` Your columns keep their names: map `jwt_id` to `accessTokenId`. Refresh tokens stored by v1 keep working: they start a session at their next rotation. See [Data provider](https://dotpress.dev/auth/data-provider.md). ### New defaults | | v1 | v2 | To keep v1 | | --------------------- | ---------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------- | | Access token lifetime | 1 hour | 15 minutes | `accessTokenTTL: 3600` | | bcrypt cost | 10 | 12 | `passwordHashRounds: 10` | | Login throttling | none | 5 failures per minute per username and IP, 100 per hour per username | `loginThrottle: false` | | Logout | every session of the user | the current session | `{ "scope": "all" }` in the body | | `username` claim | written | not written | `usernameClaim: true` | | Refresh token reuse | rejected | revokes the session (after 10 seconds of grace) | — | | Refresh token cookie | `SameSite` setting, `Path=/` | `SameSite=Strict`, `Path=/auth` | `cookies.refreshTokenSameSite`, `cookies.refreshTokenPath` | - **Throttling**: the default store is in memory. With several instances, configure a [shared store](https://dotpress.dev/auth/passwords.md#a-shared-store). Behind a proxy, the server must trust the proxy headers, or every client shares one counter per username. - **Passwords over 72 bytes** make `hashPassword()` throw, where bcrypt truncated them: check new passwords with `isPasswordTooLong()` in your schemas. Existing passwords keep working. - **Without the `username` claim**, `ctx.auth.username` is `undefined`: use `ctx.user`, or `GET /auth/me` in the frontend. - **Client IP addresses** of the login events come from `ctx.req.ip`: proxy headers count only when the server trusts them (v1 trusted them always, so addresses could be spoofed). ### Responses of the routes - **Tokens set as cookies are no longer in the body.** With the refresh token in a cookie, the body has the `accessToken` only; with both in cookies, no token. `userId`, `expiresIn` and `expiresAt` are always there. - **The access token is read from the `Authorization: Bearer` header** (or its cookie), no longer from an `accessToken` field of the body. Send the header on `/auth/logout` too. `/auth/refresh` still reads its body as before. - **Errors**: the code of an error is in the `error` field (`INVALID_LOGIN`), with a sentence in `message`. An invalid token on `/auth/refresh` or `/auth/restore` gives `401 INVALID_REFRESH_TOKEN` (v1: `500`). New: `429 TOO_MANY_LOGIN_ATTEMPTS`, with `Retry-After`, and `403 CROSS_ORIGIN_REQUEST`. - **Logout is idempotent**: without a valid token, it answers `200` and clears the cookies (v1: `401`). - **`onLoginFailed`** has a new `errorType`, `'too_many_attempts'`: an exhaustive `switch` needs a case. Its events report `clientId` instead of `client`. ### Access tokens Access tokens follow [RFC 9068](https://www.rfc-editor.org/rfc/rfc9068): | | v1 | v2 | | ------------ | -------------------------------------- | -------------------------------------------------- | | `typ` header | `JWT` | `at+jwt` | | `iss` | empty by default, not checked | `issuer`, checked | | `aud` | the client given at login, not checked | the API (`audience`, `issuer` by default), checked | | Client | `aud` | `client_id`, in `ctx.auth.clientId` | | Session | — | `sid`, in `ctx.auth.sessionId` | Services that verify the tokens themselves must accept the new `aud`, and the `at+jwt` type if they check it. ## What your users will notice | Change | Effect | To avoid it | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | | New access token format | v1 access tokens are rejected (`401`). Clients refresh as usual and get v2 tokens: sessions continue. | — | | New cookie names (`__Host-`, `__Secure-`) and path | Users of the cookie mode are logged out once. | Keep the v1 names and path, below. | | bcrypt cost of 12 | Logins take about 200 ms instead of 50 ms. Accounts still hashed with a cost of 10 answer faster than unknown usernames, until they log in again. | `passwordHashRounds: 10` | | Shorter access tokens | Clients refresh every 15 minutes. | `accessTokenTTL: 3600` | To keep the sessions of the cookie mode: ```ts cookies: { enabled: true, accessTokenName: 'dotpress_access_token', refreshTokenName: 'dotpress_refresh_token', refreshTokenPath: '/', } ``` Do not change the path of the refresh token cookie without renaming it: the browser would keep both cookies, and send both. ## Checklist - [ ] Node.js 22.12 or later, Zod 4. - [ ] `@dotpress/core` and an adapter installed; `dotpress` removed. - [ ] `createApp({ adapter })`; Express middlewares in `beforeRoutes` and `afterRoutes`. - [ ] `onError` instead of `onException`, `exposeErrors` instead of `isDev`, and the `cors` origins listed. - [ ] `params: [...]` removed; Express path syntax replaced. - [ ] Handlers return their response: no `res.json()`, `res.send()` or `res.redirect()`. - [ ] Middlewares checked: they see the raw request, and return nothing, an error or a response. - [ ] Clients read the `error` key of errors, and the new validation format. - [ ] Uploads: `files` schemas, `bodyLimit` on upload routes. - [ ] Plugins declared with `definePlugin()`. - [ ] `AppTypes` replaced by `AuthUser` and `RequestContext` augmentations. - [ ] Auth: `createAuth()` with `issuer`, PKCS#8 and SPKI keys, the new data provider methods and columns. - [ ] Auth: the new defaults reviewed (lifetimes, cost, throttling, logout, cookies). - [ ] Clients send the access token in the `Authorization` header, and no longer read tokens set as cookies from the body. - [ ] With several instances: a shared store for the login throttling. --- url: https://dotpress.dev/reference/compatibility.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Versioning and compatibility From 2.0, the packages follow [semantic versioning](https://semver.org): a minor version never breaks code written for an earlier one of the same major. They are released together, with the same version number. ## What a minor version may change - **New exports, and new optional options.** An option added to a function or a type is optional, with a default that keeps the previous behavior. - **New members of the unions you test.** Code that switches on one of these unions keeps a `default` branch, or ignores the values it does not know: | Union | Package | | ---------------------------------------------------------------- | ------------------ | | `HttpMethod`, `LogLevel` | `@dotpress/core` | | `AuthErrorCode`, `AuthRouteErrorCode`, `LoginErrorType` | `@dotpress/auth` | | `DeadReason`, `RetryReason`, `HandleResult['status']` | `@dotpress/events` | | `StoreOperation`, `CacheAccess['type']`, `CacheAccess['reason']` | `@dotpress/cache` | | `MailFormat` | `@dotpress/mailer` | - **New optional members of the contracts you implement**: `HttpAdapter`, `DataProvider`, `RateLimitStore`, `Transport`, `Source`, `CacheStore`, `MailProvider`. An implementation written for an earlier minor keeps working. - **New optional fields** of the objects Dotpress returns, like the OpenAPI document. - **Error messages.** They are written for people: test the error class, its `code` or its `status`, not its message. ## What only a major version changes - Removing or renaming an export, an option or a member. - Changing the type of an option or of a returned value, or the meaning of a default. - Adding a required member to a contract you implement. - Dropping a supported version of Node.js (22.12 and later) or of TypeScript (5.5 and later, with `strict`). ## How it is checked Each entry point of a package has an API report, committed with the code: a change of the public API shows in the pull request that makes it, and is released with a changeset of the matching level. See [CONTRIBUTING.md](https://github.com/dotpressjs/dotpress/blob/main/CONTRIBUTING.md#public-api). ## Prereleases Until 2.0, the prereleases may still break the API from one to the next: each one lists its breaking changes in the changelog of the packages. Since the beta (`2.0.0-beta.N`), the API is complete, and changes only from feedback. --- url: https://dotpress.dev/reference/design-decisions/index.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Design decisions These pages record the choices that shape Dotpress, and why they were made: the context, the decision, the alternatives that were set aside, and the consequences, good and bad. They explain why the API looks the way it does, and what to expect from it. | Decision | In short | | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | [Errors are returned](https://dotpress.dev/reference/design-decisions/returned-errors.md) | A handler returns its errors like any other value. Throwing works too, with the same response. | | [A declarative registry](https://dotpress.dev/reference/design-decisions/declarative-registry.md) | Routes are declarations, compiled at startup: conflicts are detected, and the app describes itself. | | [No decorators, no DI](https://dotpress.dev/reference/design-decisions/no-decorators.md) | Plain functions and objects, typed by inference. Services are passed explicitly, or provided by plugins. | | [A transport-agnostic core](https://dotpress.dev/reference/design-decisions/agnostic-core.md) | The core knows nothing of the HTTP server: adapters translate, on Web standards. | | [No edge runtime in 2.0](https://dotpress.dev/reference/design-decisions/edge.md) | 2.0 supports Node.js and AWS Lambda. The core stays portable, so that edge runtimes can come later. | They share a few principles: 1. **The core depends on no HTTP server.** No Express, Fastify or Hono in `@dotpress/core`. 2. **Plugins do not know their adapter.** A plugin that needs a specific server is a design smell. 3. **Services work on their own.** The mailer, the event bus and the cache run in a script or a worker, without an app. 4. **Types are inferred, not declared.** You write schemas; the types follow. 5. **Sensible defaults, everything configurable.** --- url: https://dotpress.dev/reference/design-decisions/returned-errors.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Errors are returned ## Context An API spends much of its code on refusals: the resource does not exist, the user may not see it, the input conflicts with the data. These are not exceptional: they are expected outcomes of a request, as much as a success. With exceptions as the only way out, the control flow of a handler is hidden: a `throw` deep in a service ends the request, and nothing in the handler shows it. HTTP frameworks also disagree on what happens next: Express 4 loses errors thrown by `async` handlers unless they are passed to `next()`, each framework has its own error handlers, and each app ends up with its own error format. ## Decision - **An error is a value.** `notFoundError()`, `forbiddenError()` and the other helpers return an `HttpError`, and a handler or a middleware returns it: `return notFoundError('Task not found')`. - **Throwing gives the same response.** An `HttpError` thrown by a handler, a middleware or a helper of the HTTP layer is answered exactly like a returned one. - **Services never throw an `HttpError`.** An HTTP error belongs to the HTTP layer. Services throw their own business errors, and the handler translates them into the response. - **Anything else thrown is a bug.** It is answered `500 INTERNAL_ERROR`, logged, and passed to `onError`. Its details stay out of the response, unless `exposeErrors` is enabled. - **One format for every error**: `{ status, error, message, data? }`, whether it comes from the handler, the validation, the router (`404`, `405`) or the body parser. ```ts handler: async ({ req, user }) => { const task = await tasks.find(req.params.id) if (!task) return notFoundError('Task not found') if (task.ownerId !== user.id) return forbiddenError() return task } ``` ## Business errors and HTTP errors A failed request can involve three different errors, and Dotpress keeps them apart: | Error | Example | Raised by | Becomes | | ------------------ | ---------------------------------------------------------- | ----------------------------------- | ------------------------------------------------- | | **Business error** | the task is already completed, the balance is insufficient | the service, as its own error class | the HTTP error the handler chooses | | **Process error** | the database is down, a timeout, a bug | anything | `500 INTERNAL_ERROR`, logged, passed to `onError` | | **HTTP error** | `409 CONFLICT`, `Task already completed` | the handler, or a middleware | the response the client receives | A service knows the rules of the domain, not HTTP. It signals an expected outcome by its return value (`undefined` when nothing is found), and a broken rule by a business error: ```ts import { conflictError, defineRoute, notFoundError } from '@dotpress/core' interface Task { id: string completedAt: Date | null } declare const db: { tasks: { find(id: string): Promise update(id: string, changes: Partial): Promise } } // services/tasks.ts: no HTTP here export class TaskAlreadyCompletedError extends Error {} export const completeTask = async (id: string) => { const task = await db.tasks.find(id) if (!task) return undefined if (task.completedAt) throw new TaskAlreadyCompletedError(id) return db.tasks.update(id, { completedAt: new Date() }) } // routes/tasks.ts: the HTTP translation defineRoute({ method: 'post', path: '/tasks/:id/complete', handler: async ({ req }) => { try { const task = await completeTask(req.params.id) return task ?? notFoundError('Task not found') } catch (error) { if (error instanceof TaskAlreadyCompletedError) return conflictError('Task already completed') throw error // a process error: 500, reported by onError } }, }) ``` Returning the HTTP error is what makes the separation visible: the handler is the one place where a business error becomes a response, with a status, a stable code, and a message chosen to be shown to the client. ## Alternatives considered - **Exceptions only**, with exception filters, as in NestJS. Familiar, but the exits of a handler are invisible, and a middleware cannot stop a request without throwing. - **A `Result` type** (`ok(value)` / `err(error)`), as in functional libraries. Explicit, but every call must be unwrapped, and it spreads to every service. Returning an `HttpError` gets the readability without the ceremony: a value is a success, an `HttpError` is a refusal. - **The error handlers of the HTTP server.** They differ from one server to another, and would tie the app to one of them. ## Consequences - Handlers read as guard clauses: each refusal is an early `return`, visible where it happens. - A middleware stops a request the same way: by returning an error, or a response such as `redirect()`. - Services stay free of HTTP: they run unchanged in a worker, a script or a test, and their errors describe the domain, not a status. - The client only sees messages chosen for it: the message of a business or process error never reaches the response by accident. - A business error the handler does not translate is a `500`, reported by `onError`: a forgotten case is treated as the bug it is, without leaking anything. - The translation is written in the handlers: a `try`/`catch`, or a function shared by the routes of a feature. Dotpress has no global mapping from business errors to HTTP errors. - Clients parse one error format, and the `error` code is stable: they can rely on it rather than on messages. - The return type of a handler does not list its errors, and a returned error skips the response schema. Document the errors of a route in `meta.responses`, for [OpenAPI](https://dotpress.dev/services/openapi.md). See [Errors](https://dotpress.dev/concepts/errors.md), [Errors of your services](https://dotpress.dev/routing/errors.md#errors-of-your-services) and the [error reference](https://dotpress.dev/reference/responses.md#error-helpers). --- url: https://dotpress.dev/reference/design-decisions/declarative-registry.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # A declarative registry ## Context In most HTTP frameworks, declaring a route registers a function on a server at once: `app.get('/tasks/:id', handler)`. The route only exists inside the server, in the order it was registered. Nothing can list the routes, check them against each other, or describe them, without running requests. An API needs exactly that: its documentation, its client, its tests and its security review all start from the list of its routes, with their inputs and outputs. ## Decision - **A route is a declaration**: a method, a path, schemas, middlewares, metadata and a handler, recorded by a router. Declaring it runs nothing. - **`createApp()` compiles the declarations** of its routers, checks them, and builds a request pipeline per route, before mounting them on the adapter. - **Routers are instances.** `createRouter()` creates an isolated registry, mounted with `createApp({ routers })`. - **A global router**, for small apps: `defineRoute()` and `createRouteGroup()` register on it, and `createApp()` mounts it when no `routers` are given. ## Alternatives considered - **Registering routes on the server directly.** The simplest, but it ties the routes to one server, and leaves nothing to inspect. - **A global registry only.** Convenient, but routes depend on which modules happen to be imported, two apps in a process share them, and tests are not isolated. - **File-system routing**, a file per route. Popular in full-stack frameworks, but it needs a build step or a loader, and the path of a route moves away from its code. ## Consequences - **Conflicts are detected at startup**: two routes with the same method and path make `createApp()` throw, instead of one shadowing the other. - **The app describes itself**: `app.routes` lists the mounted routes with their schemas, metadata and security, and `@dotpress/openapi` builds the OpenAPI document from them. The documentation cannot drift from the code. - **Matching is the same on every adapter**: Dotpress matches the routes itself, with the same rules everywhere. - **Tests choose their routes**: an app made of one router tests it in isolation, and several apps can live in one process. - **Plugins add routes like an app does**: `api.defineRoute()` records declarations, checked with the others. - With the global router, the modules that declare routes must be imported before `createApp()`. Explicit routers avoid this. See [How Dotpress works](https://dotpress.dev/concepts/how-it-works.md) and [Routers](https://dotpress.dev/routing/routes.md#routers). --- url: https://dotpress.dev/reference/design-decisions/no-decorators.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # No decorators, no DI ## Context Frameworks such as NestJS structure an API with classes and decorators: `@Controller()`, `@Get(':id')`, `@Body()`, `@Injectable()`, and a dependency injection container that builds the services. They bring a clear structure, at a cost: - the types of a request do not come from its validation: a DTO class, decorators for validation, and the handler signature describe the same input three times; - the behavior depends on metadata and on a container resolved at runtime, hard to follow in the code and to debug; - legacy decorators and `emitDecoratorMetadata` need a compilation step, and are not supported by tools that only strip types, such as Node.js running TypeScript directly; - tests go through the container, or rebuild it. ## Decision - **Routes, middlewares and plugins are plain objects and functions**: `defineRoute({ path, schema, handler })`, `defineMiddleware(fn)`, `definePlugin({ name, setup })`. - **Types are inferred.** The Zod schemas of a route type its `req.params`, `req.query`, `req.body` and its response; the path types its parameters; a typed middleware types what it guarantees. Nothing is declared twice. - **No container.** Services are created by your code, and passed explicitly: as arguments of a router factory, or provided in the context by a plugin (`ctx.services`, `ctx.mailer`), typed by module augmentation. - **No mandatory code generation, no compiler option.** ```ts import { createRouter } from '@dotpress/core' interface TaskService { create(input: { title: string }): Promise<{ id: string; title: string }> } export const createTasksRouter = (tasks: TaskService) => { const router = createRouter() router.defineRoute({ method: 'post', path: '/tasks', status: 201, schema: (z) => ({ body: z.object({ title: z.string().min(1) }) }), handler: ({ req }) => tasks.create(req.body), // req.body: { title: string } }) return router } ``` ## Alternatives considered - **Decorators and a container**, as in NestJS. Rejected for the reasons above; the structure they bring is kept by conventions: routers per feature, services created at startup. - **Standard decorators** (TC39, TypeScript 5). They no longer need a compiler option, but do not have parameter decorators nor type metadata: they cannot type a request from its validation. - **A lightweight container** (tsyringe, Awilix…). Nothing prevents using one with Dotpress; the framework does not need it. ## Consequences - What a route does is in its definition: no metadata to look up elsewhere. - The code runs as is with Node.js type stripping: `node src/server.ts`, without a build step. - Tests create the services they need, real or fake, and pass them: no container to configure. - Wiring is explicit: in a large app, the composition root (`createApp()` and the factories it calls) grows with the services. It is plain code, readable and refactorable. See [Typing](https://dotpress.dev/concepts/typing.md) and [Project structure](https://dotpress.dev/getting-started/project-structure.md). --- url: https://dotpress.dev/reference/design-decisions/agnostic-core.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # A transport-agnostic core ## Context Express, Fastify and Hono serve HTTP very well. What an API needs on top of them is the same everywhere: typed routes, validation, one error format, middlewares, plugins. Yet each server has its own request object, its own middleware model, its own error handling. An app written for one ends up coupled to it, and changing the server, or running the same API on AWS Lambda, means rewriting its HTTP layer. ## Decision - **`@dotpress/core` imports no HTTP server.** It works on a normalized request and returns a normalized response, made of Web standards only: `Uint8Array`, `ReadableStream`, `File`, `AbortSignal`, `crypto.randomUUID()`. - **Adapters translate.** An adapter converts the native request of its server into the normalized request, runs the pipeline of the route, and writes the normalized response. Express, Fastify, Hono and AWS Lambda each have one. - **`ctx.req` and `ctx.res` are the same on every adapter.** The native request stays available as `ctx.raw`, as an escape hatch. - **Every adapter behaves the same**: route matching, body parsing and limits, `HEAD` requests, errors, streaming. A shared [conformance suite](https://dotpress.dev/services/testing.md#writing-an-adapter) runs against each of them. - **The rule is checked in CI**: an ESLint rule forbids imports of HTTP servers and of Node.js modules (`node:*`, `Buffer`, `process`…) in the core and the service packages. Node.js-only code lives in adapters, and in separate entry points (the SMTP provider, the CLIs). - **The core reads no environment variable**: the configuration is passed to `createApp()` and to the services. ## Alternatives considered - **Building on one server**: Express, Fastify or Hono. Simpler, but every app and plugin would be coupled to it, and no server is the best choice everywhere: on AWS Lambda, for instance. - **Exposing the native objects in the context.** Convenient, but every handler and plugin using them would depend on one server again. `ctx.raw` keeps the door open, explicitly. ## Consequences - The routes, middlewares and plugins of an app run unchanged on Express, Fastify, Hono and AWS Lambda: the server becomes a deployment choice. See [Choosing an adapter](https://dotpress.dev/adapters/index.md). - Plugins are written once, for every adapter. - Handlers return their response instead of writing it: the same code produces the same response everywhere, and tests run without a server. - Native middlewares of a server still work, registered on the adapter (`beforeRoutes`), but they tie that part of the app to it. - Features specific to one server (Fastify schemas, Hono's typed client) are not used by Dotpress routes. - Writing an adapter is a contained task: the `HttpAdapter` contract and the conformance suite define it. See [How Dotpress works](https://dotpress.dev/concepts/how-it-works.md) and [Adapters](https://dotpress.dev/adapters/index.md). --- url: https://dotpress.dev/reference/design-decisions/edge.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # No edge runtime in 2.0 ## Context Edge runtimes (Cloudflare Workers, Deno Deploy, Vercel Edge…) run JavaScript close to the users, on Web-standard APIs. Bun and Deno also run servers, with their own APIs. Supporting a runtime is more than code that happens to run on it. Each one has its own limits (CPU time per request, memory, bundle size, available Node.js APIs), its own way to deploy, and its own behavior for streaming, disconnections and background work. Supporting it means running the test suite on it in CI, documenting how to deploy, and answering the issues it raises. ## Decision - **Dotpress 2.0 supports Node.js and AWS Lambda.** CI runs every package on Node.js 22, 24 and 26, and the conformance suite on every adapter, including the three Lambda triggers. Both have deployment guides. - **The core stays portable.** `@dotpress/core` and the service packages only use Web-standard APIs, checked by an ESLint rule (see [A transport-agnostic core](https://dotpress.dev/reference/design-decisions/agnostic-core.md)). The main entry of `@dotpress/adapter-hono` only relies on Hono and Web standards, and `adapter.fetch` handles a Web `Request`. - **Other runtimes are not officially supported yet**: they may work, but are not tested. ## Alternatives considered - **Supporting edge runtimes in 2.0.** It would have spread the testing and the documentation over several runtimes before the API is stable, while many APIs need what edge runtimes limit: database connections, long requests, Node.js libraries. - **Ignoring edge runtimes.** Using Node.js APIs freely in the core would have made adding them later a rewrite. ## Consequences - An API deployed on Node.js or AWS Lambda is on the supported path, with its deployment guides. - Running on Bun, Deno or an edge runtime is possible through `adapter.fetch` of the Hono adapter, at your own risk: report what you find in an issue. - Some providers already talk to edge services over HTTP: the Upstash and Workers KV stores of the cache, Cloudflare Queues for events. - Adding a runtime later is an addition, not a rewrite: an entry point for the adapter, the conformance suite in CI, and a deployment guide. See [Hono › Other runtimes](https://dotpress.dev/adapters/hono.md#other-runtimes). --- url: https://dotpress.dev/examples/index.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Examples Runnable apps, from one feature to a complete API. Each one is tested by the CI of the repository, and its code is imported in these pages when the site is built: what you read is what runs. | Example | What it shows | Server | | ------------------------------------------------------- | -------------------------------------------------------------------------- | ------- | | [Express](https://dotpress.dev/examples/express.md) | Routes, validation, returned errors, OpenAPI and Scalar | Express | | [Fastify](https://dotpress.dev/examples/fastify.md) | Dotpress routes on an existing Fastify instance, on Node.js and AWS Lambda | Fastify | | [Hono](https://dotpress.dev/examples/hono.md) | One app on Node.js and AWS Lambda, with native Hono middlewares | Hono | | [Authentication](https://dotpress.dev/examples/auth.md) | Sign-up, login, token rotation, cookie sessions, roles, logout | Express | | [Events](https://dotpress.dev/examples/events.md) | Events emitted by an API, listeners run by a worker through Redis | Fastify | | [Mailer](https://dotpress.dev/examples/mailer.md) | A contact form sending multilingual MJML emails, with previews and SMTP | Hono | | [Cache](https://dotpress.dev/examples/cache.md) | Memo and batching per request, cache with tags and grace period, Redis | Express | | [Tasks API](https://dotpress.dev/examples/tasks-api.md) | A team task manager: every package in one app, organized by feature | Fastify | Start with the example of your server, then the one of the feature you need. The [Tasks API](https://dotpress.dev/examples/tasks-api.md) shows how they fit together in a real project. ## Run an example Every example requires Node.js 22.18 or later, which runs the TypeScript sources directly. Copy it with [degit](https://github.com/Rich-Harris/degit), then install it with your package manager: ```sh npx degit dotpressjs/dotpress/examples/express my-api cd my-api npm install npm run dev ``` In every example, `npm test` runs the tests and `npm run typecheck` checks the types. The examples that use Redis or an SMTP server work without them: their `compose.yaml` starts them for development. --- url: https://dotpress.dev/examples/express.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Express A small tasks API on [Express](https://expressjs.com): - typed routes in a group (`/tasks`), with parameters, query and body validated by Zod schemas; - errors returned by the handlers (`notFoundError()`, `conflictError()`), documented in `meta.responses`; - an OpenAPI 3.1 document generated from the routes (`/openapi.json`), and its Scalar API reference (`/docs`); - tests of the app in memory with `@dotpress/testing`, and on the real Express server. Source: [`examples/express`](https://github.com/dotpressjs/dotpress/tree/main/examples/express). ## Run it ```sh npx degit dotpressjs/dotpress/examples/express my-api cd my-api npm install npm run dev ``` ## The routes ```ts file="/../examples/express/src/routes.ts" import { conflictError, createRouter, empty, notFoundError, } from '@dotpress/core' import { z } from 'zod' import type { TaskStore } from './tasks.ts' // A schema with an identifier is declared once in the OpenAPI document // (components/schemas), and referenced by the routes. const Task = z .object({ id: z.uuid(), title: z.string(), done: z.boolean(), createdAt: z.iso.datetime(), }) .meta({ id: 'Task', description: 'A task to do' }) const Title = z.string().trim().min(1).max(200) const TASK_NOT_FOUND = 'Task not found' const DUPLICATE_TITLE = 'A task with this title already exists' /** * Routes of the tasks. The store is a parameter: tests and environments * give their own, without a dependency injection container. */ export const tasksRouter = (store: TaskStore) => { const router = createRouter() const tasks = router.createGroup('/tasks') tasks.defineRoute({ path: '/', schema: (z) => ({ query: z.object({ done: z.stringbool().optional() }), response: z.array(Task), }), meta: { summary: 'List the tasks', tags: ['tasks'] }, // req.query: { done?: boolean } handler: ({ req }) => store.list({ done: req.query.done }), }) tasks.defineRoute({ method: 'post', path: '/', status: 201, schema: (z) => ({ body: z.object({ title: Title }), response: Task, }), meta: { summary: 'Create a task', tags: ['tasks'], responses: { 409: DUPLICATE_TITLE }, }, handler: async ({ req }) => { // Errors are returned, not thrown: they are part of the handler type. if (await store.findByTitle(req.body.title)) { return conflictError(DUPLICATE_TITLE) } return store.create(req.body.title) }, }) tasks.defineRoute({ path: '/:id', schema: () => ({ response: Task }), meta: { summary: 'Get a task', tags: ['tasks'], responses: { 404: TASK_NOT_FOUND }, }, // req.params: { id: string }, from the path handler: async ({ req }) => (await store.get(req.params.id)) ?? notFoundError(TASK_NOT_FOUND), }) tasks.defineRoute({ method: 'patch', path: '/:id', schema: (z) => ({ body: z.object({ title: Title.optional(), done: z.boolean().optional() }), response: Task, }), meta: { summary: 'Update a task', tags: ['tasks'], responses: { 404: TASK_NOT_FOUND, 409: DUPLICATE_TITLE }, }, handler: async ({ req }) => { const { title } = req.body if (title !== undefined) { const existing = await store.findByTitle(title) if (existing && existing.id !== req.params.id) { return conflictError(DUPLICATE_TITLE) } } return ( (await store.update(req.params.id, req.body)) ?? notFoundError(TASK_NOT_FOUND) ) }, }) tasks.defineRoute({ method: 'delete', path: '/:id', status: 204, meta: { summary: 'Delete a task', tags: ['tasks'], responses: { 404: TASK_NOT_FOUND }, }, handler: async ({ req }) => (await store.remove(req.params.id)) ? empty() : notFoundError(TASK_NOT_FOUND), }) return router } ``` ## The app The app takes its adapter as a parameter: Express in `server.ts`, the memory adapter of `@dotpress/testing` in the tests. ```ts file="/../examples/express/src/app.ts" import { createApp, type HttpAdapter, type Logger } from '@dotpress/core' import { openapiPlugin } from '@dotpress/openapi' import { tasksRouter } from './routes.ts' import { createTaskStore, type TaskStore } from './tasks.ts' export interface TasksAppOptions { adapter: TAdapter store?: TaskStore logger?: Logger } /** * Creates the app on any adapter: Express in `server.ts`, the memory * adapter of `@dotpress/testing` in the tests. */ export const createTasksApp = ({ adapter, store = createTaskStore(), logger, }: TasksAppOptions) => createApp({ adapter, ...(logger && { logger }), routers: [tasksRouter(store)], plugins: [ // GET /openapi.json: the OpenAPI document, GET /docs: the Scalar page openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0' }, tags: [{ name: 'tasks', description: 'Tasks to do' }], }), ], }) ``` ## The server ```ts file="/../examples/express/src/server.ts" import { expressAdapter } from '@dotpress/adapter-express' import { createTasksApp } from './app.ts' const port = Number(process.env.PORT ?? 3000) const app = await createTasksApp({ adapter: expressAdapter() }) await app.listen(port) console.log(`Tasks API: http://localhost:${port}/tasks`) console.log(`API reference: http://localhost:${port}/docs`) // Waits for pending requests, then runs the onClose hooks of the plugins. for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, () => void app.close()) } ``` ## Learn more - [The Express adapter](https://dotpress.dev/adapters/express.md) - [Validation](https://dotpress.dev/routing/validation.md) - [OpenAPI](https://dotpress.dev/services/openapi.md) --- url: https://dotpress.dev/examples/fastify.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Fastify A small notes API, with its Dotpress routes mounted on an existing [Fastify](https://fastify.dev) instance, and served by Node.js or by AWS Lambda: - Dotpress routes next to a native Fastify route (`/health`), with a Fastify hook applied to both; - one app, two entries: `server.ts` for Node.js, `lambda.ts` for AWS Lambda; - tests with `inject()` of Fastify, over HTTP, and on simulated API Gateway events, without an AWS account. Source: [`examples/fastify`](https://github.com/dotpressjs/dotpress/tree/main/examples/fastify). ## Run it ```sh npx degit dotpressjs/dotpress/examples/fastify my-api cd my-api npm install npm run dev ``` ```sh curl -X POST localhost:3000/notes -H 'content-type: application/json' -d '{"text":"Hello"}' curl localhost:3000/notes curl localhost:3000/health ``` ## The routes The routes receive their store as an argument, and know nothing about the server: ```ts file="/../examples/fastify/src/routes.ts" import { createRouter, notFoundError } from '@dotpress/core' import { z } from 'zod' import type { NoteStore } from './notes.ts' const Note = z.object({ id: z.uuid(), text: z.string(), createdAt: z.iso.datetime(), }) /** Dotpress routes: they know nothing about Fastify or AWS Lambda. */ export const notesRouter = (store: NoteStore) => { const router = createRouter() router.defineRoute({ path: '/notes', schema: (z) => ({ response: z.array(Note) }), handler: () => store.list(), }) router.defineRoute({ method: 'post', path: '/notes', status: 201, schema: (z) => ({ body: z.object({ text: z.string().trim().min(1).max(1000) }), response: Note, }), handler: ({ req }) => store.create(req.body.text), }) router.defineRoute({ path: '/notes/:id', schema: () => ({ response: Note }), handler: async ({ req }) => (await store.get(req.params.id)) ?? notFoundError('Note not found'), }) return router } ``` ## The app The Fastify instance keeps its own routes and hooks: `beforeRoutes` registers what must also apply to the Dotpress routes. ```ts file="/../examples/fastify/src/app.ts" import { fastifyAdapter } from '@dotpress/adapter-fastify' import { createApp, type Logger } from '@dotpress/core' import Fastify from 'fastify' import { createNoteStore } from './notes.ts' import { notesRouter } from './routes.ts' /** * Mounts the Dotpress routes on a Fastify instance, next to its native * routes. Used by the server (`server.ts`) and the Lambda handler * (`lambda.ts`). */ export const createNotesApp = (options: { logger?: Logger } = {}) => { // An existing instance: its plugins, hooks and native routes stay. const fastify = Fastify() fastify.get('/health', async () => ({ status: 'ok' })) return createApp({ adapter: fastifyAdapter({ app: fastify, // Hooks and plugins registered here apply to the Dotpress routes too. beforeRoutes: (app) => { app.addHook('onRequest', async (request, reply) => { reply.header('x-request-id', request.id) }) }, }), ...(options.logger && { logger: options.logger }), routers: [notesRouter(createNoteStore())], }) } ``` ## Two entries On Node.js, the server closes gracefully on `SIGTERM`: ```ts file="/../examples/fastify/src/server.ts" import { createNotesApp } from './app.ts' const port = Number(process.env.PORT ?? 3000) const app = await createNotesApp() await app.listen(port) console.log(`Notes API: http://localhost:${port}/notes`) // Closes the Fastify instance once the pending requests are served. for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, () => void app.close()) } ``` On AWS Lambda, the same app, created at the first invocation: ```ts file="/../examples/fastify/src/lambda.ts" import { createLambdaHandler } from '@dotpress/adapter-fastify/lambda' import { createNotesApp } from './app.ts' // API Gateway (REST and HTTP APIs), Function URLs and Application Load // Balancers. The app is created at the first invocation (cold start), then // reused by the next invocations of the execution environment. export const handler = createLambdaHandler(() => createNotesApp()) ``` `npm run build:lambda` bundles the handler with esbuild into `dist/lambda.mjs`, about 300 kB gzipped with Fastify. Fastify is a CommonJS package: the script defines `require` for it. See [Bundle the handler](https://dotpress.dev/adapters/aws-lambda.md#bundle-the-handler) and [Deployment › AWS Lambda](https://dotpress.dev/deployment/aws-lambda.md). ## Learn more - [The Fastify adapter](https://dotpress.dev/adapters/fastify.md) - [The AWS Lambda adapter](https://dotpress.dev/adapters/aws-lambda.md) - [Testing](https://dotpress.dev/routing/testing.md) --- url: https://dotpress.dev/examples/hono.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Hono The same notes API on [Hono](https://hono.dev): one app, served by Node.js or by AWS Lambda. - native Hono middlewares (`secureHeaders()`) applied to the Dotpress routes, and a native Hono route (`/health`); - two entries: `node.ts` with `@hono/node-server`, `lambda.ts` with the main entry of the adapter, which has no Node.js server; - tests in memory with `adapter.fetch()` (Web `Request` and `Response`), over HTTP, and on simulated API Gateway events. Source: [`examples/hono`](https://github.com/dotpressjs/dotpress/tree/main/examples/hono). ## Run it ```sh npx degit dotpressjs/dotpress/examples/hono my-api cd my-api npm install npm run dev ``` ```sh curl -X POST localhost:3000/notes -H 'content-type: application/json' -d '{"text":"Hello"}' curl localhost:3000/notes curl localhost:3000/health ``` ## The routes The same routes as the [Fastify example](https://dotpress.dev/examples/fastify.md), unchanged: they do not depend on the server. ```ts file="/../examples/hono/src/routes.ts" import { createRouter, notFoundError } from '@dotpress/core' import { z } from 'zod' import type { NoteStore } from './notes.ts' const Note = z.object({ id: z.uuid(), text: z.string(), createdAt: z.iso.datetime(), }) /** Dotpress routes: they know nothing about Hono or AWS Lambda. */ export const notesRouter = (store: NoteStore) => { const router = createRouter() router.defineRoute({ path: '/notes', schema: (z) => ({ response: z.array(Note) }), handler: () => store.list(), }) router.defineRoute({ method: 'post', path: '/notes', status: 201, schema: (z) => ({ body: z.object({ text: z.string().trim().min(1).max(1000) }), response: Note, }), handler: ({ req }) => store.create(req.body.text), }) router.defineRoute({ path: '/notes/:id', schema: () => ({ response: Note }), handler: async ({ req }) => (await store.get(req.params.id)) ?? notFoundError('Note not found'), }) return router } ``` ## The app The app takes its adapter as a parameter: the options of the adapter are shared, the adapter itself comes from the entry. ```ts file="/../examples/hono/src/app.ts" import type { HonoAdapterOptions } from '@dotpress/adapter-hono' import { createApp, type HttpAdapter, type Logger } from '@dotpress/core' import type { Hono } from 'hono' import { secureHeaders } from 'hono/secure-headers' import { createNoteStore } from './notes.ts' import { notesRouter } from './routes.ts' /** Options of the Hono adapter, the same on Node.js and AWS Lambda. */ export const honoOptions: HonoAdapterOptions = { // Native Hono middlewares and routes, before the Dotpress routes. beforeRoutes: (app) => { app.use('*', secureHeaders()) app.get('/health', (c) => c.json({ status: 'ok' })) }, } /** * Creates the app on a Hono adapter: `honoAdapter()` of * `@dotpress/adapter-hono/node` in `node.ts`, of `@dotpress/adapter-hono` * in `lambda.ts` and the tests. */ export const createNotesApp = ( adapter: TAdapter, options: { logger?: Logger } = {} ) => createApp({ adapter, ...(options.logger && { logger: options.logger }), routers: [notesRouter(createNoteStore())], }) ``` ## Two entries ```ts file="/../examples/hono/src/node.ts" // The Node.js entry: @hono/node-server serves the app. import { honoAdapter } from '@dotpress/adapter-hono/node' import { createNotesApp, honoOptions } from './app.ts' const port = Number(process.env.PORT ?? 3000) const app = await createNotesApp(honoAdapter(honoOptions)) await app.listen(port) console.log(`Notes API: http://localhost:${port}/notes`) // Waits for pending requests, then runs the onClose hooks of the plugins. for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, () => void app.close()) } ``` ```ts file="/../examples/hono/src/lambda.ts" // The AWS Lambda entry: API Gateway (REST and HTTP APIs), Function URLs and // Application Load Balancers. The main entry of the adapter has no Node.js // server: the bundle stays small. import { honoAdapter } from '@dotpress/adapter-hono' import { createLambdaHandler } from '@dotpress/adapter-hono/lambda' import { createNotesApp, honoOptions } from './app.ts' // The app is created at the first invocation (cold start), then reused by // the next invocations of the execution environment. export const handler = createLambdaHandler(() => createNotesApp(honoAdapter(honoOptions)) ) ``` `npm run build:lambda` bundles the handler into `dist/lambda.mjs`: about 115 kB gzipped, Hono and Zod included, the smallest of the adapters. See [Choosing an adapter](https://dotpress.dev/adapters/index.md). ## Learn more - [The Hono adapter](https://dotpress.dev/adapters/hono.md) - [The AWS Lambda adapter](https://dotpress.dev/adapters/aws-lambda.md) - [Deployment › AWS Lambda](https://dotpress.dev/deployment/aws-lambda.md) --- url: https://dotpress.dev/examples/auth.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Authentication A private notes API with `@dotpress/auth`, on Express: - sign-up, login, and the access token in the `Authorization` header, for mobile apps and other services; - cookie sessions for browsers: both tokens in `httpOnly` cookies, protected against cross-site request forgery; - refresh token rotation, with the session revoked when a used refresh token comes back; - logout of the current device or of every device, and a password change that logs out every device; - routes for authenticated users (`requireAuth`), and for admins (`requireRole('admin')`); - the OpenAPI document and the Scalar page, with the guarded routes marked as secured. Source: [`examples/auth`](https://github.com/dotpressjs/dotpress/tree/main/examples/auth). ## Run it ```sh npx degit dotpressjs/dotpress/examples/auth my-api cd my-api npm install ADMIN_PASSWORD='choose a long passphrase' npm run dev ``` Without `JWT_PRIVATE_KEY` and `JWT_PUBLIC_KEY`, a temporary key pair is generated at startup: tokens stop working at each restart. `ADMIN_PASSWORD` creates an `admin` account. ```sh curl -X POST localhost:3000/users -H 'content-type: application/json' \ -d '{"username":"alice","password":"correct horse battery staple"}' curl -X POST localhost:3000/auth/login -H 'content-type: application/json' \ -d '{"username":"alice","password":"correct horse battery staple"}' # { "accessToken": "…", "refreshToken": "…", "expiresIn": 900, … } curl localhost:3000/notes -H 'authorization: Bearer ' ``` `http://localhost:3000/docs` lists every route: log in there, then paste the access token in the Authorize dialog. ## The service `createAuth()` with the keys, the issuer and the data provider. The type of `ctx.user` is declared here, once: ```ts file="/../examples/auth/src/auth.ts" import { createAuth, type KeyPairOptions } from '@dotpress/auth' import type { Store } from './store.ts' // Type of ctx.user: what dataProvider.findUserById() returns. declare module '@dotpress/auth' { interface AuthUser { id: string username: string roles: string[] } } export interface AuthOptions { keys: KeyPairOptions store: Store /** `iss` claim of the tokens: the URL of the API, per environment. */ issuer: string /** bcrypt cost. Defaults to 12 (about 200 ms per login). */ passwordHashRounds?: number } export const createAuthService = ({ keys, store, issuer, passwordHashRounds, }: AuthOptions) => createAuth({ keys, issuer, dataProvider: store.dataProvider, ...(passwordHashRounds !== undefined && { passwordHashRounds }), // Clients choose at login: { mode: 'cookie' } for browsers (both tokens // in httpOnly cookies, out of reach of the JavaScript of the page), the // body otherwise (mobile apps, other services). cookies: { enabled: true, accessTokenInCookie: true }, }) ``` The data provider (`src/store.ts`) keeps the users and the refresh tokens in memory: replace it with your database, as in the [SQL data provider](https://dotpress.dev/auth/data-provider.md#an-sql-data-provider) of the Tasks API. ## The app ```ts file="/../examples/auth/src/app.ts" import { authPlugin } from '@dotpress/auth' import { createApp, type HttpAdapter, type Logger } from '@dotpress/core' import { openapiPlugin } from '@dotpress/openapi' import { createAuthService, type AuthOptions } from './auth.ts' import { createNoteStore, type NoteStore } from './notes.ts' import { adminRouter, notesRouter, usersRouter } from './routes.ts' export interface NotesAppOptions< TAdapter extends HttpAdapter, > extends AuthOptions { adapter: TAdapter notes?: NoteStore logger?: Logger } /** * Creates the app on any adapter: Express in `server.ts`, the memory * adapter of `@dotpress/testing` in the tests. */ export const createNotesApp = ({ adapter, notes = createNoteStore(), logger, ...authOptions }: NotesAppOptions) => { const auth = createAuthService(authOptions) return createApp({ adapter, ...(logger && { logger }), routers: [ usersRouter(auth, authOptions.store), notesRouter(notes), adminRouter(authOptions.store), ], plugins: [ // Reads the access token of every request (ctx.user, ctx.auth), and // serves /auth/login, /auth/refresh, /auth/me, /auth/restore and // /auth/logout. authPlugin(auth), // The routes guarded by requireAuth and requireRole() are documented // as secured: Scalar shows an Authorize button. openapiPlugin({ info: { title: 'Notes API', version: '1.0.0' }, tags: [ { name: 'auth', description: 'Sessions' }, { name: 'users', description: 'Accounts' }, { name: 'notes', description: 'Private notes' }, { name: 'admin', description: 'Administration' }, ], }), ], }) } ``` ## The routes Sign-up validates the password length for bcrypt, a password change revokes every session, and each user only sees their own notes: ```ts file="/../examples/auth/src/routes.ts" import { conflictError, createRouter, empty, forbiddenError, notFoundError, } from '@dotpress/core' import { isPasswordTooLong, requireAuth, requireRole, type Auth, } from '@dotpress/auth' import { z } from 'zod' import type { Note as StoredNote, NoteStore } from './notes.ts' import type { Store, User } from './store.ts' // bcrypt reads 72 bytes at most: longer passwords get a validation error // instead of being truncated. const Password = z .string() .min(12) .refine((password) => !isPasswordTooLong(password), 'Password too long') const PublicUser = z .object({ id: z.uuid(), username: z.string(), role: z.enum(['user', 'admin']), createdAt: z.iso.datetime(), }) .meta({ id: 'User' }) const Note = z .object({ id: z.uuid(), text: z.string(), createdAt: z.iso.datetime() }) .meta({ id: 'Note' }) /** Never returns the password hash. */ const toPublicUser = ({ id, username, role, createdAt }: User) => ({ id, username, role, createdAt, }) /** The owner is the authenticated user: not returned. */ const toPublicNote = ({ id, text, createdAt }: StoredNote) => ({ id, text, createdAt, }) const USERNAME_TAKEN = 'This username is already taken' const NOTE_NOT_FOUND = 'Note not found' /** Sign-up and password change. */ export const usersRouter = (auth: Auth, store: Store) => { const router = createRouter() router.defineRoute({ method: 'post', path: '/users', status: 201, schema: (z) => ({ body: z.object({ username: z.string().trim().min(3).max(50), password: Password, }), response: PublicUser, }), meta: { summary: 'Sign up', tags: ['users'], responses: { 409: USERNAME_TAKEN }, }, handler: async ({ req }) => { if (await store.users.findByUsername(req.body.username)) { return conflictError(USERNAME_TAKEN) } const user = await store.users.create({ username: req.body.username, passwordHash: await auth.hashPassword(req.body.password), }) return toPublicUser(user) }, }) router.defineRoute({ method: 'put', path: '/users/me/password', status: 204, // ctx.user is defined and typed in the handler. middlewares: [requireAuth], schema: (z) => ({ body: z.object({ currentPassword: z.string(), newPassword: Password }), }), meta: { summary: 'Change the password, and log out every device', tags: ['users'], responses: { 403: 'Invalid current password' }, }, handler: async ({ req, user }) => { const stored = await store.users.get(user.id) if ( !(await auth.verifyPassword( req.body.currentPassword, stored?.passwordHash )) ) { return forbiddenError('Invalid current password') } await store.users.setPasswordHash( user.id, await auth.hashPassword(req.body.newPassword) ) // A stolen session must not survive a password change. await auth.revokeUserSessions(user.id) return empty() }, }) return router } /** Notes of the authenticated user: every route of the group requires it. */ export const notesRouter = (notes: NoteStore) => { const router = createRouter() const group = router.createGroup('/notes', [requireAuth]) group.defineRoute({ path: '/', schema: (z) => ({ response: z.array(Note) }), meta: { summary: 'List my notes', tags: ['notes'] }, handler: async ({ user }) => (await notes.listByOwner(user.id)).map(toPublicNote), }) group.defineRoute({ method: 'post', path: '/', status: 201, schema: (z) => ({ body: z.object({ text: z.string().trim().min(1).max(1000) }), response: Note, }), meta: { summary: 'Create a note', tags: ['notes'] }, handler: async ({ req, user }) => toPublicNote(await notes.create(user.id, req.body.text)), }) group.defineRoute({ path: '/:id', schema: () => ({ response: Note }), meta: { summary: 'Get a note', tags: ['notes'], responses: { 404: NOTE_NOT_FOUND }, }, handler: async ({ req, user }) => { const note = await notes.get(req.params.id) // The notes of other users answer 404, not 403: their existence is // not revealed. if (!note || note.ownerId !== user.id) { return notFoundError(NOTE_NOT_FOUND) } return toPublicNote(note) }, }) return router } /** Administration: admins only (401 without user, 403 without the role). */ export const adminRouter = (store: Store) => { const router = createRouter() router.createGroup('/admin', [requireRole('admin')]).defineRoute({ path: '/users', schema: (z) => ({ response: z.array(PublicUser) }), meta: { summary: 'List the users', tags: ['admin'] }, handler: async () => (await store.users.list()).map(toPublicUser), }) return router } ``` ## Body or cookies The client chooses at login: | Login body | Tokens | Next requests | | ---------------------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------- | | `{ username, password }` | in the response body | `Authorization: Bearer `; `POST /auth/refresh` with both tokens in the body | | `{ username, password, mode: 'cookie' }` | in `httpOnly` cookies, never in the body | the browser sends the cookies; `POST /auth/restore` when the page loads | In cookie mode, the API accepts the cookies from its own origin only. A front-end served from another origin must be allowed by the `cors` option of the app, with `credentials: true`. ## Before production - Give the key pair in `JWT_PRIVATE_KEY` and `JWT_PUBLIC_KEY`, from the secrets of your platform, and the URL of the API in `JWT_ISSUER`. - Replace the in-memory stores with your database, and give the login throttle a [shared store](https://dotpress.dev/auth/passwords.md#a-shared-store) when you run several instances. - Go through the [security checklist](https://dotpress.dev/auth/security.md). ## Learn more - [Authentication](https://dotpress.dev/auth/index.md) - [Sessions and tokens](https://dotpress.dev/auth/sessions.md) - [Cookie mode and CSRF](https://dotpress.dev/auth/cookies.md) - [Protecting routes](https://dotpress.dev/auth/protecting-routes.md) --- url: https://dotpress.dev/examples/events.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Events An orders API with `@dotpress/events`, on Fastify. Placing an order emits an `order.placed` event; its two listeners run later, in a worker, through a Redis queue ([BullMQ](https://docs.bullmq.io)): - the API answers without waiting for the listeners: it only queues one message per listener; - `send-order-confirmation` logs the confirmation, and `notify-warehouse` calls a warehouse service over HTTP, with an idempotency key; - a listener that throws is retried (3 attempts, exponential backoff), then kept in the failed jobs of the queue; - without Redis, an in-memory queue runs the listeners in the API process: nothing to install to try it. Source: [`examples/events`](https://github.com/dotpressjs/dotpress/tree/main/examples/events). ## Run it ```sh npx degit dotpressjs/dotpress/examples/events my-api cd my-api npm install npm run dev ``` ```sh curl -X POST localhost:3000/orders -H 'content-type: application/json' \ -d '{"items":[{"sku":"BOOK-1","quantity":2}]}' ``` The logs of the API show the listeners running. ### With Redis ```sh docker compose up -d # Redis REDIS_URL=redis://localhost:6379 npm run dev # terminal 1: the API REDIS_URL=redis://localhost:6379 npm run worker # terminal 2: the worker ``` Stop the worker, place orders, then start it again: it handles the orders that waited in the queue. `npm run worker` runs `dotpress-events work src/worker.ts --watch`. ## The event and its listeners Shared by the API and the worker. `load` imports the code of a listener in the worker only: ```ts file="/../examples/events/src/events.ts" import { defineEvent, defineListener } from '@dotpress/events' import { z } from 'zod' // Shared by the API, which emits, and by the worker, which runs the // listeners. /** A fact: an order was placed. Payloads travel as JSON. */ export const orderPlaced = defineEvent({ name: 'order.placed', schema: z.object({ orderId: z.uuid(), items: z.array(z.object({ sku: z.string(), quantity: z.number().int() })), }), }) // Each listener gets its own message: it is retried on its own. `load` // keeps the code of the listeners out of the API, which only needs their // names. export const sendOrderConfirmation = defineListener(orderPlaced, { name: 'send-order-confirmation', load: () => import('./listeners/send-order-confirmation.ts'), }) export const notifyWarehouse = defineListener(orderPlaced, { name: 'notify-warehouse', load: () => import('./listeners/notify-warehouse.ts'), }) export const listeners = [sendOrderConfirmation, notifyWarehouse] ``` A listener can run twice: the message `id` is the idempotency key sent to the warehouse service. ```ts file="/../examples/events/src/listeners/notify-warehouse.ts" import type { EventPayload, ListenerContext } from '@dotpress/events' import type { orderPlaced } from '../events.ts' /** * Sends the order to the warehouse service (`WAREHOUSE_URL`). When the * service fails, the listener throws: the message is retried, then kept in * the failed jobs of the queue. */ export default async ({ payload, id, logger, }: ListenerContext>) => { const url = process.env.WAREHOUSE_URL if (!url) { logger.info( { orderId: payload.orderId }, 'WAREHOUSE_URL is not set: the warehouse is not notified' ) return } const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', // A message can be delivered twice (retry after a timeout): the id // is the same for every attempt, so the service ignores duplicates. 'idempotency-key': id, }, body: JSON.stringify(payload), signal: AbortSignal.timeout(10_000), }) if (!res.ok) throw new Error(`The warehouse answered ${res.status}`) logger.info({ orderId: payload.orderId }, 'Warehouse notified') } ``` ## Emitting The route stores the order, then emits: an event describes something that happened. ```ts file="/../examples/events/src/routes.ts" import { createRouter, notFoundError } from '@dotpress/core' import { z } from 'zod' import { orderPlaced } from './events.ts' import type { OrderStore } from './orders.ts' const Order = z .object({ id: z.uuid(), items: z.array(z.object({ sku: z.string(), quantity: z.number().int() })), createdAt: z.iso.datetime(), }) .meta({ id: 'Order' }) const ORDER_NOT_FOUND = 'Order not found' export const ordersRouter = (store: OrderStore) => { const router = createRouter() const orders = router.createGroup('/orders') orders.defineRoute({ method: 'post', path: '/', status: 201, schema: (z) => ({ body: z.object({ items: z .array( z.object({ sku: z.string().trim().min(1).max(64), quantity: z.number().int().min(1).max(1000), }) ) .min(1), }), response: Order, }), meta: { summary: 'Place an order', tags: ['orders'] }, // ctx.events comes from eventsPlugin. handler: async ({ req, events }) => { // Store first, then emit: an event describes something that // happened. With a database, emit after the transaction commits. const order = await store.create(req.body.items) // Returns once the messages are queued: the listeners run later, in // the worker, and the client does not wait for them. await events.emit(orderPlaced, { orderId: order.id, items: order.items }) return order }, }) orders.defineRoute({ path: '/:id', schema: () => ({ response: Order }), meta: { summary: 'Get an order', tags: ['orders'], responses: { 404: ORDER_NOT_FOUND }, }, handler: async ({ req }) => (await store.get(req.params.id)) ?? notFoundError(ORDER_NOT_FOUND), }) return router } ``` The transport comes from the configuration: BullMQ with `REDIS_URL`, an in-memory queue without it. ```ts file="/../examples/events/src/bus.ts" import { createEventBus, createMemoryTransport, type EventBusOptions, type Transport, } from '@dotpress/events' import { createBullmqTransport } from '@dotpress/events/bullmq' import { listeners } from './events.ts' type Env = Record /** Name of the BullMQ queue, shared by the API and the worker. */ export const queueName = (env: Env = process.env) => env.EVENTS_QUEUE ?? 'events' /** BullMQ connection options from a Redis URL (`redis://` or `rediss://`). */ export const redisConnection = (redisUrl: string) => { const url = new URL(redisUrl) return { host: url.hostname, port: Number(url.port || 6379), ...(url.username && { username: decodeURIComponent(url.username) }), ...(url.password && { password: decodeURIComponent(url.password) }), ...(url.pathname.length > 1 && { db: Number(url.pathname.slice(1)) }), ...(url.protocol === 'rediss:' && { tls: {} }), } } /** A transport, and how to close it on shutdown. */ export type ClosableTransport = Transport & { close(): Promise } /** * With `REDIS_URL`, the events go to a BullMQ queue, handled by the worker * (`npm run worker`). Without it, an in-memory queue runs the listeners in * this process: development without Redis. */ export const createTransport = (env: Env = process.env): ClosableTransport => { if (env.REDIS_URL) { return createBullmqTransport({ queue: queueName(env), // While Redis is unreachable, emit() fails at once. connection: { ...redisConnection(env.REDIS_URL), enableOfflineQueue: false, }, }) } const memory = createMemoryTransport() // Waits for the listeners in progress. return Object.assign(memory, { close: () => memory.drain() }) } /** The event bus of the API. */ export const createBus = ( transport: Transport, options: Pick = {} ) => createEventBus({ transport, listeners, ...options }) ``` ## The worker ```ts file="/../examples/events/src/worker.ts" import { createConsoleLogger } from '@dotpress/core' import { createWorker } from '@dotpress/events' import { createBullmqSource } from '@dotpress/events/bullmq' import { queueName, redisConnection } from './bus.ts' import { listeners } from './events.ts' // Entry of `dotpress-events work src/worker.ts`: reads the BullMQ queue and // runs the listeners, until Ctrl+C or SIGTERM (it then finishes the jobs in // progress). In production, run it in its own container. const redisUrl = process.env.REDIS_URL if (!redisUrl) { throw new Error( 'REDIS_URL is required: without it, the API runs the listeners itself.' ) } export const logger = createConsoleLogger({ bindings: { process: 'worker' } }) export default { worker: createWorker({ listeners, logger, // The attempts of the BullMQ jobs (3 by default): the last failure is // reported as final, for alerts. maxAttempts: 3, onFailure: (error, { envelope, attempt, final }) => { if (final) { logger.error( { error, listener: envelope?.listener, id: envelope?.id, attempt }, 'Event listener gave up: the job stays in the failed jobs' ) } }, }), source: createBullmqSource({ queue: queueName(), connection: redisConnection(redisUrl), concurrency: 5, }), logger, } ``` In production, run the API and the worker as two processes, with `dotpress-events work src/worker.ts` (without `--watch`). On `SIGTERM`, the worker finishes the jobs in progress before exiting. ## Learn more - [Events and workers](https://dotpress.dev/services/events.md) - [Deployment › Event workers](https://dotpress.dev/deployment/event-workers.md): SQS, pg-boss, Cloudflare Queues, Pub/Sub, Service Bus - [Testing helpers](https://dotpress.dev/services/testing.md#events) --- url: https://dotpress.dev/examples/mailer.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Mailer A contact form with `@dotpress/mailer`, on Hono. Each message sends two emails, written in [MJML](https://mjml.io): - a notification to the team, with the visitor as reply-to address: the team answers with the Reply button; - an acknowledgement to the visitor, in their language (`Accept-Language: fr-CA` gets the French version); - a shared layout, translated texts, and a text version converted from the HTML one; - the message of the visitor escaped in the HTML version; - previews of the templates in the browser, in development; - SMTP with `SMTP_URL`, and [Mailpit](https://mailpit.axllent.org) to see the delivered emails in development. Source: [`examples/mailer`](https://github.com/dotpressjs/dotpress/tree/main/examples/mailer). ## Run it ```sh npx degit dotpressjs/dotpress/examples/mailer my-api cd my-api npm install npm run dev ``` ```sh curl -X POST localhost:3000/contact -H 'content-type: application/json' \ -H 'accept-language: fr' \ -d '{"name":"Alex","email":"alex@example.com","message":"Hello"}' ``` Without `SMTP_URL`, the emails are printed in the terminal. `http://localhost:3000/previews` shows each template in each language, with sample data. ### With Mailpit ```sh docker compose up -d # Mailpit SMTP_URL=smtp://localhost:1025 npm run dev ``` The emails appear at `http://localhost:8025`, as an email client would show them. ## A template The schema types the data of the email: a missing field is a type error where the email is sent. ```ts file="/../examples/mailer/src/mails/contact-received.ts" import { defineTemplate } from '@dotpress/mailer' import { z } from 'zod' import { baseLayout } from './layout.ts' /** * Sent to the visitor, in their language. It does not repeat the message: * otherwise, anyone could send any text to any address through the form. */ export const contactReceived = defineTemplate({ name: 'contactReceived', layout: baseLayout, schema: z.object({ name: z.string() }), // {{name}} is inserted by Mustache, after the translations. subject: { en: 'We received your message, {{name}}', fr: 'Nous avons bien reçu votre message, {{name}}', }, translations: { greeting: { en: 'Hello {{name}},', fr: 'Bonjour {{name}},' }, body: { en: 'Thank you for contacting us. We will answer within two business days.', fr: 'Merci de nous avoir contactés. Nous vous répondrons sous deux jours ouvrés.', }, signature: { en: 'The Example team', fr: 'L’équipe Example' }, }, mjml: ({ t }) => ` ${t('greeting')} ${t('body')} ${t('signature')} `, }) ``` The acknowledgement does not repeat the message: otherwise, anyone could send any text to any address through the form. In production, protect the form against abuse as well (rate limit, CAPTCHA). ## The provider SMTP with `SMTP_URL`, the console in development only: in production, a missing configuration fails at startup instead of losing the emails. ```ts file="/../examples/mailer/src/mailer.ts" import { createConsoleProvider, createMailer, type MailProvider, } from '@dotpress/mailer' import { createSmtpProvider } from '@dotpress/mailer/smtp' type Env = Record /** * With `SMTP_URL`, the messages are sent over SMTP: Mailpit in development * (compose.yaml), your email service in production (most of them have an * SMTP interface). Without it, they are printed, in development only: in * production, a missing configuration must fail at startup, not lose the * messages. */ export const createProvider = ( env: Env = process.env ): MailProvider & { close?(): void } => { if (env.SMTP_URL) return createSmtpProvider(env.SMTP_URL) if (env.NODE_ENV === 'production') { throw new Error('SMTP_URL is required.') } return createConsoleProvider() } /** The mailer: `mailerPlugin` gives it the logger of each request. */ export const createAppMailer = ( provider: MailProvider, from = 'Example ' ) => createMailer({ provider, from, defaultLocale: 'en' }) ``` To use the HTTP API of your email service instead of SMTP, replace `createSmtpProvider()` with its provider, for example `createPostmarkProvider()` of `@dotpress/mailer/postmark`: the templates and the routes do not change. ## The routes ```ts file="/../examples/mailer/src/routes.ts" import { createRouter, empty, notFoundError, text } from '@dotpress/core' import type { Mailer } from '@dotpress/mailer' import { negotiateLocale } from './locale.ts' import { contactNotification, contactReceived, previews, type PreviewName, } from './mails/index.ts' /** The contact form: one email to the team, one to the visitor. */ export const contactRouter = (contactTo: string) => { const router = createRouter() router.defineRoute({ method: 'post', path: '/contact', status: 204, schema: (z) => ({ body: z.object({ name: z.string().trim().min(1).max(100), email: z.email(), message: z.string().trim().min(1).max(5000), }), }), meta: { summary: 'Send a message to the team', tags: ['contact'] }, // ctx.mailer comes from mailerPlugin, and logs with the request logger. handler: async ({ req, mailer }) => { const { name, email, message } = req.body // fr-CA,fr;q=0.9 → fr; unsupported languages → the default locale. const locale = negotiateLocale( req.header('accept-language'), contactReceived.locales ) await mailer.send(contactNotification, { to: contactTo, // The team answers the visitor with the Reply button. replyTo: { name, address: email }, data: { name, email, message, locale: locale ?? 'en' }, }) await mailer.send(contactReceived, { to: { name, address: email }, locale, data: { name }, }) return empty() }, }) return router } const previewNames = Object.keys(previews) as PreviewName[] const page = (html: string) => text(html, { headers: { 'content-type': 'text/html; charset=utf-8' } }) /** * Previews of the templates in the browser, with sample data: for * development only. */ export const previewsRouter = (mailer: Mailer) => { const router = createRouter() router.defineRoute({ path: '/previews', handler: () => page( `Email previews
    ${previewNames .flatMap((name) => previews[name].locales.map( (locale) => `
  • ${name} (${locale})
  • ` ) ) .join('')}
` ), }) router.defineRoute({ path: '/previews/:template', schema: (z) => ({ query: z.object({ locale: z.string().optional() }), }), handler: async ({ req }) => { const name = req.params.template if (!(previewNames as string[]).includes(name)) { return notFoundError('Unknown template') } const mail = await previews[name as PreviewName].render( mailer, req.query.locale ) return page(mail.html) }, }) return router } ``` The previews are not served when `NODE_ENV` is `production`. ## Learn more - [Emails](https://dotpress.dev/services/mailer.md) - [Testing helpers](https://dotpress.dev/services/testing.md#emails) --- url: https://dotpress.dev/examples/cache.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Cache An articles API with `@dotpress/cache`, on Express, using the two tools of the package: - **the memo** (`ctx.memo`): a value loaded once per request. The middleware and the handler share the current user, and a list loads the authors of its articles with one query, not one per article; - **the cache** (`ctx.cache`): values kept across requests and instances. Articles are cached for 10 minutes; editing an article expires it, and renaming a user expires every article at once, with tags; - **a grace period**: when the database fails, an expired article is still served for one more day, instead of an error; - Redis with `REDIS_URL`, the memory of the process otherwise. A fake database records its queries: the tests count them, as you would watch the queries of your database. Source: [`examples/cache`](https://github.com/dotpressjs/dotpress/tree/main/examples/cache). ## Run it ```sh npx degit dotpressjs/dotpress/examples/cache my-api cd my-api npm install npm run dev ``` ```sh curl localhost:3000/articles # loads, then caches for 1 minute curl localhost:3000/articles/a1 # cached for 10 minutes curl -X PATCH localhost:3000/articles/a1 -H 'x-user-id: u1' \ -H 'content-type: application/json' -d '{"title":"Caching 102"}' # expires it curl -X PATCH localhost:3000/users/me -H 'x-user-id: u1' \ -H 'content-type: application/json' -d '{"name":"Alice Martin"}' # expires every article ``` The `x-user-id` header stands in for authentication: see the [Authentication example](https://dotpress.dev/examples/auth.md) for the real thing. ### With Redis ```sh docker compose up -d # Redis REDIS_URL=redis://localhost:6379 npm run dev ``` The cache now survives restarts, and is shared by every instance of the API. ## The memo and the cache entries ```ts file="/../examples/cache/src/loaders.ts" import { defineCacheEntry, defineMemo, type Memo } from '@dotpress/cache' import { z } from 'zod' import type { Article, Database } from './db.ts' /** * Memo of the users: loaded once per request, and in batches. The ids * requested in the same tick are loaded with one query. */ export const userMemo = (db: Database) => defineMemo({ name: 'user', batch: async (ids: readonly string[]) => { const users = await db.users.findManyById(ids) // A Map by id: unknown ids give undefined. return new Map(users.map((user) => [user.id, user])) }, }) export type UserMemo = ReturnType export const ArticleView = z .object({ id: z.string(), title: z.string(), author: z.object({ id: z.string(), name: z.string() }).nullable(), updatedAt: z.iso.datetime(), }) .meta({ id: 'Article' }) /** An article with the name of its author, as the API returns it. */ export const toView = async ( memo: Memo, users: UserMemo, article: Article ): Promise> => { const author = await memo(users, article.authorId) return { id: article.id, title: article.title, author: author ? { id: author.id, name: author.name } : null, updatedAt: article.updatedAt, } } // Values shared across requests and instances. Every view of an article // holds the name of its author: renaming a user expires them all with the // `articles` tag. /** One article: 10 minutes, then served for one more day if the database fails. */ export const articleCache = defineCacheEntry({ name: 'article', key: (id: string) => id, // Values read back are checked: a value written by an older version of // the app that no longer matches is a miss, not a crash. schema: ArticleView, ttl: '10m', grace: '1d', tags: (id: string) => [`article:${id}`, 'articles'], }) /** The list of the articles. */ export const articleListCache = defineCacheEntry({ name: 'article-list', key: () => 'all', schema: z.array(ArticleView), ttl: '1m', tags: () => ['articles', 'article-list'], }) ``` ## The routes The list combines both tools: the cache keeps it for a minute, and on a miss, the memo loads its authors with one query. Updates expire what they change. ```ts file="/../examples/cache/src/routes.ts" import { createRouter, defineMiddleware, forbiddenError, notFoundError, unauthorizedError, type RequestContext, } from '@dotpress/core' import type { Database } from './db.ts' import { articleCache, articleListCache, ArticleView, toView, type UserMemo, } from './loaders.ts' /** * The current user, from the `x-user-id` header: a stand-in for real * authentication (see the auth example). Memoized: the middleware and the * handler share one query. */ const viewerOf = (ctx: RequestContext, users: UserMemo) => { const id = ctx.req.header('x-user-id') return id ? ctx.memo(users, id) : undefined } export const articlesRouter = (db: Database, users: UserMemo) => { const router = createRouter() const requireViewer = defineMiddleware(async (ctx) => (await viewerOf(ctx, users)) ? undefined : unauthorizedError() ) router.defineRoute({ path: '/articles', schema: (z) => ({ response: z.array(ArticleView) }), meta: { summary: 'List the articles', tags: ['articles'] }, handler: ({ cache, memo }) => cache.getOrSet(articleListCache, async () => { const articles = await db.articles.list() // One query for every author, not one per article: the memo // batches the ids requested together. return Promise.all( articles.map((article) => toView(memo, users, article)) ) }), }) router.defineRoute({ path: '/articles/:id', schema: () => ({ response: ArticleView }), meta: { summary: 'Get an article', tags: ['articles'], responses: { 404: 'Article not found' }, }, handler: async ({ req, cache, memo }) => { const { id } = req.params // `undefined` (unknown article) is not cached. const view = await cache.getOrSet(articleCache, id, async () => { const article = await db.articles.findById(id) return article && toView(memo, users, article) }) return view ?? notFoundError('Article not found') }, }) router.defineRoute({ method: 'patch', path: '/articles/:id', middlewares: [requireViewer], schema: (z) => ({ body: z.object({ title: z.string().trim().min(1).max(200) }), response: ArticleView, }), meta: { summary: 'Rename an article (its author only)', tags: ['articles'], responses: { 403: 'Not the author', 404: 'Article not found' }, }, handler: async (ctx) => { const { req, cache, memo } = ctx const { id } = req.params const article = await db.articles.findById(id) if (!article) return notFoundError('Article not found') // Loaded by the middleware: no new query. const viewer = await viewerOf(ctx, users) if (article.authorId !== viewer?.id) return forbiddenError() const updated = await db.articles.update(id, req.body.title) // This article, and the list that shows its title. await cache.invalidateTags([`article:${id}`, 'article-list']) return toView(memo, users, updated!) }, }) router.defineRoute({ method: 'patch', path: '/users/me', middlewares: [requireViewer], schema: (z) => ({ body: z.object({ name: z.string().trim().min(1).max(100) }), }), meta: { summary: 'Rename the current user', tags: ['users'] }, handler: async (ctx) => { const viewer = await viewerOf(ctx, users) const user = await db.users.rename(viewer!.id, ctx.req.body.name) // Every cached article shows the name of its author. await ctx.cache.invalidateTags(['articles']) ctx.memo.set(users, user!.id, user) return user }, }) return router } ``` ## The app The cache fails open: when Redis is down or slower than 200 ms, requests go to the database, and the failures are logged. ```ts file="/../examples/cache/src/app.ts" import { createCache, type CacheStore } from '@dotpress/cache' import { cachePlugin } from '@dotpress/cache/plugin' import { createApp, type HttpAdapter, type Logger } from '@dotpress/core' import { createDatabase, type Database } from './db.ts' import { userMemo } from './loaders.ts' import { articlesRouter } from './routes.ts' export interface ArticlesAppOptions { adapter: TAdapter store: CacheStore db?: Database /** Prefix of the keys in the store. Defaults to `articles`. */ prefix?: string logger?: Logger } /** * Creates the app on any adapter: Express in `server.ts`, the memory * adapter of `@dotpress/testing` in the tests. */ export const createArticlesApp = ({ adapter, store, db = createDatabase(), prefix = 'articles', logger, }: ArticlesAppOptions) => { const cache = createCache({ store, prefix, // A slow store counts as a failure: the cache fails open, the request // goes on with the database. storeTimeout: '200ms', }) return createApp({ adapter, ...(logger && { logger }), routers: [articlesRouter(db, userMemo(db))], // ctx.memo: a new memo for each request. ctx.cache: the cache, logging // with the request logger. plugins: [cachePlugin({ cache })], }) } ``` ## What the tests check The tests count the queries of the fake database: ```ts file="/../examples/cache/test/memo.test.ts" import { afterEach, beforeEach, expect, it } from 'vitest' import { startApp } from './support.ts' // ctx.memo: a value is loaded once per request, and the ids requested // together are loaded in one query. let api: Awaited> beforeEach(async () => { api = await startApp() }) afterEach(() => api.close()) it('loads the authors of a list with one query, not one per article', async () => { const queries = await api.queriesOf(async () => { const res = await api.request('/articles') expect(await res.json()).toEqual([ expect.objectContaining({ id: 'a1', author: { id: 'u1', name: 'Alice' }, }), expect.objectContaining({ id: 'a2', author: { id: 'u2', name: 'Bob' } }), expect.objectContaining({ id: 'a3', author: { id: 'u1', name: 'Alice' }, }), ]) }) // 3 articles, 2 distinct authors: one batch. expect(queries).toEqual(['articles.list', 'users.findManyById']) }) it('shares the current user between the middleware and the handler', async () => { const queries = await api.queriesOf(async () => { const res = await api.patch('/articles/a1', { title: 'Caching 102' }, 'u1') expect(res.status).toBe(200) }) // The middleware loads the user, the handler reads it from the memo, and // the view of the article reuses it for the author. expect(queries.filter((query) => query.startsWith('users.'))).toEqual([ 'users.findManyById', ]) }) it('starts a new memo for each request', async () => { const queries = await api.queriesOf(async () => { await api.patch('/articles/a1', { title: 'One' }, 'u1') await api.patch('/articles/a1', { title: 'Two' }, 'u1') }) expect(queries.filter((query) => query.startsWith('users.'))).toHaveLength(2) }) it('rejects unknown users, and other authors', async () => { expect((await api.patch('/articles/a1', { title: 'X' })).status).toBe(401) expect( (await api.patch('/articles/a1', { title: 'X' }, 'nobody')).status ).toBe(401) expect((await api.patch('/articles/a1', { title: 'X' }, 'u2')).status).toBe( 403 ) }) ``` ## Learn more - [Cache and memoization](https://dotpress.dev/services/cache.md) - [Deployment › Several instances](https://dotpress.dev/deployment/node.md#several-instances) --- url: https://dotpress.dev/examples/tasks-api.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Tasks API A team task manager: every package of Dotpress assembled in one app, organized as a real project. It runs on Fastify and [SQLite](https://nodejs.org/api/sqlite.html), built into Node.js. | Package | Role in the app | | --------------------------- | ------------------------------------------------------------------------------------------ | | `@dotpress/core` | Routes and nested route groups, validation, errors returned by the handlers | | `@dotpress/adapter-fastify` | The HTTP server | | `@dotpress/auth` | Sign-up, login, access and refresh tokens, `ctx.user` | | `@dotpress/cache` | The membership checked once per request, assignees loaded in batches, the dashboard cached | | `@dotpress/events` | `task.assigned` and `task.completed`, handled by listeners in a worker, through Redis | | `@dotpress/mailer` | The notification emails, in MJML, in the language of each recipient | | `@dotpress/openapi` | The OpenAPI document and the Scalar page, with the secured routes | Source: [`examples/tasks-api`](https://github.com/dotpressjs/dotpress/tree/main/examples/tasks-api). ## The story 1. **Alice and Bob sign up.** Bob's browser speaks French: his account is in French. 2. **Alice creates the "Website launch" project, and adds Bob.** Only the owner adds members. 3. **Alice creates a task, and assigns it to Bob.** The assignee must be a member of the project. The route emits `task.assigned` and answers at once: a listener, in the worker, emails Bob in French. 4. **Bob lists his tasks**, with the name of each assignee: the names of a whole list are loaded with one query. 5. **Bob completes the task.** The route emits `task.completed`: Alice, who created the task, gets an email in English. 6. **Alice opens the dashboard** of the project. It is cached for 5 minutes, and expired at once when a task changes. Eve, who is not a member, gets `404` on every route of the project: its existence is not revealed. `test/scenario.test.ts` runs this story. ## Run it ```sh npx degit dotpressjs/dotpress/examples/tasks-api my-api cd my-api npm install npm run seed # Alice, Bob and the "Website launch" project npm run dev ``` Open `http://localhost:3000/docs`, log in with `POST /auth/login` (`alice@example.com` or `bob@example.com`, password `correct horse battery staple`), then paste the access token in the Authorize dialog. Without Redis, the listeners run in the API process, and the emails are printed in its terminal. ### With Redis and Mailpit The production setup: the API queues the events in Redis, a worker runs the listeners, and the emails go over SMTP to [Mailpit](https://mailpit.axllent.org), at `http://localhost:8025`. ```sh docker compose up -d # Redis and Mailpit export REDIS_URL=redis://localhost:6379 SMTP_URL=smtp://localhost:1025 npm run dev # terminal 1: the API npm run worker # terminal 2: the worker ``` ## The routes ```text POST /users sign up (public) /auth/login, /refresh, /me, /logout the auth plugin /projects group: requireAuth POST / GET / create, list my projects /:projectId nested group: + requireMember (404 for non-members) GET / the project and its members POST /members add a member (owner only) GET /stats the dashboard (cached) /projects/:projectId/tasks group: requireAuth, requireMember POST / GET / create, list (?status=, ?assignee=) /tasks group: requireAuth GET /:id PATCH /:id the membership is checked once the task is loaded ``` ## Project structure The code is organized by feature: each folder holds the routes, the data access, the events and the emails of its feature. See [Project structure](https://dotpress.dev/getting-started/project-structure.md). ```text src/ config.ts the settings, from the environment, validated by Zod services/ the services, created by functions (not singletons) http/ server.ts entry point of the API: config → services → app → listen app.ts the app: plugins and routers routes.ts the routers of the features, and the health check services-plugin.ts ctx.services, typed in every handler worker.ts entry point of the worker (dotpress-events work) db/ the SQLite connection and the schema features/ auth/ the authentication service, its data provider, the keys users/ sign-up, language of the user, the memo of the users projects/ projects, members, access rules, the cached dashboard tasks/ tasks, their routes and their events notifications/ the listeners of the task events, and their emails ``` ## The app Each entry point creates its services once, and gives them to the app: the API in `server.ts`, each test its own, in memory. ```ts file="/../examples/tasks-api/src/http/app.ts" import { authPlugin, type KeyPairOptions } from '@dotpress/auth' import { createCache, type CacheStore } from '@dotpress/cache' import { cachePlugin } from '@dotpress/cache/plugin' import { createApp, type HttpAdapter, type Logger } from '@dotpress/core' import type { EventBus } from '@dotpress/events' import { eventsPlugin } from '@dotpress/events/plugin' import { openapiPlugin } from '@dotpress/openapi' import { createAuthService } from '../features/auth/auth.ts' import type { Repositories } from '../services/index.ts' import { routers } from './routes.ts' import { servicesPlugin } from './services-plugin.ts' export interface TasksAppOptions { adapter: TAdapter /** The repositories of `createRepositories()`, over one database. */ repositories: Repositories keys: KeyPairOptions /** Public URL of the API: the issuer of the tokens. */ publicUrl: string cacheStore: CacheStore /** The event bus of `services/bus.ts`, or a fake bus in tests. */ events: EventBus /** bcrypt cost: lower in the tests. Defaults to 12. */ passwordHashRounds?: number logger?: Logger } /** * The HTTP app, on any adapter: Fastify in `server.ts`, the memory adapter * of `@dotpress/testing` in the tests. Its services come from the caller: * the entry point in production, each test in the tests. */ export const createTasksApp = ( options: TasksAppOptions ) => { const { adapter, repositories, logger } = options const auth = createAuthService({ db: repositories.db, users: repositories.users, keys: options.keys, issuer: options.publicUrl, passwordHashRounds: options.passwordHashRounds, }) const cache = createCache({ store: options.cacheStore, prefix: 'tasks-api', // A slow store counts as a failure: the request goes on without cache. storeTimeout: '200ms', }) return createApp({ adapter, ...(logger && { logger }), routers, plugins: [ // ctx.services: the repositories, the memos and auth of the app. servicesPlugin({ ...repositories, auth }), // ctx.user and ctx.auth; /auth/login, /refresh, /me, /logout. authPlugin(auth), // ctx.memo (per request) and ctx.cache. cachePlugin({ cache }), // ctx.events: emits with the request logger and request ID. eventsPlugin(options.events), // /openapi.json and /docs: the routes guarded by requireAuth are // marked as secured. openapiPlugin({ info: { title: 'Tasks API', version: '1.0.0', description: 'A team task manager built with Dotpress. Sign up with `POST /users`, log in with `POST /auth/login`, then use the access token with the Authorize button.', }, tags: [ { name: 'auth', description: 'Sessions' }, { name: 'users', description: 'Accounts' }, { name: 'projects', description: 'Projects, members and dashboards' }, { name: 'tasks', description: 'Tasks of the projects' }, { name: 'health', description: 'Monitoring' }, ], }), ], }) } ``` The handlers find the services in `ctx.services`, typed by module augmentation: the route files stay plain modules, without singletons to import. ```ts file="/../examples/tasks-api/src/http/services-plugin.ts" import { declareContextKey, definePlugin } from '@dotpress/core' import type { AppServices } from '../services/index.ts' // ctx.services, typed in every handler and middleware: the IDE completes // its repositories and their methods. Module augmentation applies to the // whole program, like the plugins of Dotpress do for ctx.mailer or // ctx.cache. declare module '@dotpress/core' { interface RequestContext { /** The services of the app (src/services): repositories, memos, auth. */ services: AppServices } } // Using ctx.services in an app without the plugin throws an explicit error. declareContextKey('services', 'servicesPlugin') /** * Exposes the services of the app to the routes: the route files are plain * modules, without singletons, and the tests give their own services. */ export const servicesPlugin = (services: AppServices) => definePlugin({ name: 'services', setup(api) { api.decorateContext('services', () => services) }, }) ``` ## Access rules `requireMember` checks the membership once for every route of a project, and memoizes the role: a handler that reads it again, to check the owner, makes no other query. ```ts file="/../examples/tasks-api/src/features/projects/access.ts" import { defineMemo } from '@dotpress/cache' import { defineMiddleware, notFoundError, unauthorizedError, type RequestContext, } from '@dotpress/core' import type { ProjectRepository } from './repository.ts' /** * The role of a user in a project, loaded once per request (`ctx.memo`): * the middleware, the handlers and the checks of the assignees share it. */ export const roleMemo = (projects: ProjectRepository) => defineMemo({ name: 'project-role', load: (projectId: string, userId: string) => projects.findRole(projectId, userId), }) /** * The role of the current user in a project, or undefined for a * non-member: the routes then answer 404, so that the existence of the * project is not revealed. */ export const roleIn = ( ctx: Pick & { user: { id: string } }, projectId: string ) => ctx.memo(ctx.services.loaders.role, projectId, ctx.user.id) /** * Middleware of the routes of a project (`/projects/:projectId/...`): a * non-member gets 404. The role is memoized, so the handlers read it again * without a query. */ export const requireMember = defineMiddleware(async (ctx) => { const { projectId } = ctx.req.params const { user } = ctx if (!user) return unauthorizedError() if (!projectId || !(await roleIn({ ...ctx, user }, projectId))) { return notFoundError('Project not found') } }) ``` ## The task routes Nested groups, typed path parameters, returned errors, and events emitted after the changes are stored: ```ts file="/../examples/tasks-api/src/features/tasks/routes.ts" import { requireAuth } from '@dotpress/auth' import { createRouter, notFoundError, unprocessableError, type RequestContext, } from '@dotpress/core' import { z } from 'zod' import { requireMember, roleIn } from '../projects/access.ts' import { projectTag } from '../projects/stats.ts' import { personOf, PersonView } from '../users/loaders.ts' import { taskAssigned, taskCompleted } from './events.ts' import type { Task } from './repository.ts' const Status = z.enum(['todo', 'doing', 'done']) const TaskView = z .object({ id: z.uuid(), projectId: z.uuid(), title: z.string(), status: Status, assignee: PersonView.nullable(), createdAt: z.iso.datetime(), updatedAt: z.iso.datetime(), }) .meta({ id: 'Task' }) const Title = z.string().trim().min(1).max(200) const TASK_NOT_FOUND = 'Task not found' const NOT_A_MEMBER = 'The assignee is not a member of the project' /** What the helpers read in the context of a request. */ type Context = Pick /** A task as the API returns it, with the name of its assignee. */ const toView = async ({ memo, services }: Context, task: Task) => ({ id: task.id, projectId: task.projectId, title: task.title, status: task.status, assignee: await personOf(memo, services.loaders.user, task.assigneeId), createdAt: task.createdAt, updatedAt: task.updatedAt, }) /** An assignee must be a member of the project (memoized check). */ const isMember = async ( { memo, services }: Context, projectId: string, userId: string ) => (await memo(services.loaders.role, projectId, userId)) !== undefined /** * The routes of the tasks: a plain module. The handlers find the services * of the app in ctx.services. */ export const tasksRouter = createRouter() // /projects/:projectId/tasks: the tasks of a project, for its members. const projectTasks = tasksRouter.createGroup('/projects/:projectId/tasks', [ requireAuth, requireMember, ]) projectTasks.defineRoute({ method: 'post', path: '/', status: 201, schema: (z) => ({ body: z.object({ title: Title, assigneeId: z.uuid().optional() }), response: TaskView, }), meta: { summary: 'Create a task', tags: ['tasks'], responses: { 404: 'Project not found', 422: NOT_A_MEMBER }, }, // ctx.events: eventsPlugin, with the request ID in the metadata. handler: async (ctx) => { const { req, user, cache, events, services } = ctx const { projectId } = req.params const { title, assigneeId } = req.body if (assigneeId && !(await isMember(ctx, projectId, assigneeId))) { return unprocessableError(NOT_A_MEMBER) } const task = await services.tasks.create({ projectId, title, assigneeId: assigneeId ?? null, createdBy: user.id, }) await cache.invalidateTags([projectTag(projectId)]) // After the write: the event describes something that happened. The // response does not wait for the email, sent by a listener. if (assigneeId && assigneeId !== user.id) { await events.emit(taskAssigned, { taskId: task.id, assigneeId, assignedBy: user.id, }) } return toView(ctx, task) }, }) projectTasks.defineRoute({ path: '/', schema: (z) => ({ query: z.object({ status: Status.optional(), assignee: z.uuid().optional(), }), response: z.array(TaskView), }), meta: { summary: 'List the tasks of a project', tags: ['tasks'], responses: { 404: 'Project not found' }, }, handler: async (ctx) => { const { req, services } = ctx const list = await services.tasks.listByProject(req.params.projectId, { status: req.query.status, assigneeId: req.query.assignee, }) // The assignees of every task in one query: the memo batches them. return Promise.all(list.map((task) => toView(ctx, task))) }, }) // /tasks/:id: the project is not in the path, so the membership is checked // in the handlers, once the task is loaded. const taskGroup = tasksRouter.createGroup('/tasks', [requireAuth]) taskGroup.defineRoute({ path: '/:id', schema: () => ({ response: TaskView }), meta: { summary: 'Get a task', tags: ['tasks'], responses: { 404: TASK_NOT_FOUND }, }, handler: async (ctx) => { const task = await ctx.services.tasks.findById(ctx.req.params.id) if (!task || !(await roleIn(ctx, task.projectId))) { return notFoundError(TASK_NOT_FOUND) } return toView(ctx, task) }, }) taskGroup.defineRoute({ method: 'patch', path: '/:id', schema: (z) => ({ body: z.object({ title: Title.optional(), status: Status.optional(), // null: unassigned. assigneeId: z.uuid().nullable().optional(), }), response: TaskView, }), meta: { summary: 'Update a task: title, status, assignee', tags: ['tasks'], responses: { 404: TASK_NOT_FOUND, 422: NOT_A_MEMBER }, }, handler: async (ctx) => { const { req, user, cache, events, services } = ctx const task = await services.tasks.findById(req.params.id) if (!task || !(await roleIn(ctx, task.projectId))) { return notFoundError(TASK_NOT_FOUND) } const { assigneeId } = req.body if (assigneeId && !(await isMember(ctx, task.projectId, assigneeId))) { return unprocessableError(NOT_A_MEMBER) } const updated = (await services.tasks.update(task.id, req.body))! await cache.invalidateTags([projectTag(task.projectId)]) if ( updated.assigneeId && updated.assigneeId !== task.assigneeId && updated.assigneeId !== user.id ) { await events.emit(taskAssigned, { taskId: task.id, assigneeId: updated.assigneeId, assignedBy: user.id, }) } if (updated.status === 'done' && task.status !== 'done') { await events.emit(taskCompleted, { taskId: task.id, completedBy: user.id, }) } return toView(ctx, updated) }, }) ``` ## Notifications Events carry identifiers, not data: the listeners load what they need, ignore messages already handled or outdated, and throw to be retried. ```ts file="/../examples/tasks-api/src/features/notifications/listeners.ts" import { defineListener } from '@dotpress/events' import type { Mailer } from '@dotpress/mailer' import { get, run } from '../../db/database.ts' import type { Repositories } from '../../services/index.ts' import { taskAssigned, taskCompleted } from '../tasks/events.ts' import { taskAssignedMail, taskCompletedMail } from './mails.ts' /** * The listeners of the task events: they email the people concerned. They * run in the worker (with Redis), or in the API process (without): both * create them with their own services. */ export const createNotifications = ({ repositories: { db, users, projects, tasks }, mailer, }: { repositories: Repositories mailer: Mailer }) => { /** * Sends once per message: queues deliver a message at least once, and a * retry after a timeout must not send a second email. A crash between * the email and the insert can still send one twice, never lose one. */ const once = async (messageId: string, send: () => Promise) => { if (get(db, 'SELECT 1 FROM handled_messages WHERE id = ?', messageId)) { return } await send() run( db, 'INSERT INTO handled_messages (id, handled_at) VALUES (?, ?)', messageId, new Date().toISOString() ) } const notifyAssignee = defineListener(taskAssigned, { name: 'notify-assignee', handle: async ({ payload, id, logger }) => { const [task, assignee, actor] = await Promise.all([ tasks.findById(payload.taskId), users.findById(payload.assigneeId), users.findById(payload.assignedBy), ]) // Reassigned or deleted since the event: nothing to say any more. if (!task || !assignee || !actor || task.assigneeId !== assignee.id) { return } const project = await projects.findById(task.projectId) await once(id, () => mailer.withContext({ logger }).send(taskAssignedMail, { to: { name: assignee.name, address: assignee.email }, locale: assignee.locale, data: { recipientName: assignee.name, actorName: actor.name, taskTitle: task.title, projectName: project?.name ?? '', }, }) ) }, }) const notifyCreator = defineListener(taskCompleted, { name: 'notify-creator', handle: async ({ payload, id, logger }) => { const task = await tasks.findById(payload.taskId) // Reopened since the event, or completed by its creator. if ( !task || task.status !== 'done' || task.createdBy === payload.completedBy ) { return } const [creator, actor, project] = await Promise.all([ users.findById(task.createdBy), users.findById(payload.completedBy), projects.findById(task.projectId), ]) if (!creator || !actor) return await once(id, () => mailer.withContext({ logger }).send(taskCompletedMail, { to: { name: creator.name, address: creator.email }, locale: creator.locale, data: { recipientName: creator.name, actorName: actor.name, taskTitle: task.title, projectName: project?.name ?? '', }, }) ) }, }) return [notifyAssignee, notifyCreator] } ``` ```ts file="/../examples/tasks-api/src/worker.ts" import { createConsoleLogger } from '@dotpress/core' import { createWorker } from '@dotpress/events' import { createBullmqSource } from '@dotpress/events/bullmq' import { loadConfig, requireInProduction } from './config.ts' import { openDatabase } from './db/database.ts' import { createNotifications } from './features/notifications/listeners.ts' import { redisConnection } from './services/bus.ts' import { createRepositories } from './services/index.ts' import { createAppMailer, createMailProvider } from './services/mailer.ts' // Entry of `dotpress-events work src/worker.ts` (npm run worker): reads the // BullMQ queue and runs the listeners, until Ctrl+C or SIGTERM, which wait // for the jobs in progress. It opens the same SQLite file as the API. const config = loadConfig() requireInProduction(config, ['SMTP_URL']) if (!config.REDIS_URL) { throw new Error( 'REDIS_URL is required: without it, the API runs the listeners itself.' ) } export const logger = createConsoleLogger({ bindings: { process: 'worker' } }) // The services of the worker: the database and the mailer only. const repositories = createRepositories(openDatabase(config.DATABASE_PATH)) const mailer = createAppMailer(createMailProvider(config), config.MAIL_FROM) export default { worker: createWorker({ listeners: createNotifications({ repositories, mailer }), logger, // The attempts of the BullMQ jobs (3 by default): the last failure is // reported as final, for alerts. maxAttempts: 3, onFailure: (error, { envelope, attempt, final }) => { if (final) { logger.error( { error, listener: envelope?.listener, id: envelope?.id, attempt }, 'Notification given up: the job stays in the failed jobs' ) } }, }), source: createBullmqSource({ queue: config.EVENTS_QUEUE, connection: redisConnection(config.REDIS_URL), concurrency: 5, }), logger, } ``` ## Why SQLite `node:sqlite` needs nothing to install, runs real SQL (tables, foreign keys, transactions), gives each test its own database in memory, and lets the API, the worker and the seed script open the same file. For production with several instances, use a database server: the repositories are asynchronous, so replacing SQLite with Postgres changes their queries, not their callers. `node:sqlite` is still experimental in Node.js 22, which prints an `ExperimentalWarning` once; Node.js 24 and later do not. ## Learn more - [Configuration and graceful shutdown](https://dotpress.dev/deployment/node.md), with the `config.ts` and `server.ts` of this example - [An SQL data provider](https://dotpress.dev/auth/data-provider.md#an-sql-data-provider), from this example - The examples of each feature, closer to the details: [Authentication](https://dotpress.dev/examples/auth.md), [Events](https://dotpress.dev/examples/events.md), [Mailer](https://dotpress.dev/examples/mailer.md), [Cache](https://dotpress.dev/examples/cache.md) --- url: https://dotpress.dev/deployment/aws-lambda.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # AWS Lambda On AWS Lambda, the API runs in functions that AWS starts on demand: no server to manage, and a cost that follows the traffic. This page covers the infrastructure; for the handler and the bundle, see [the Lambda adapter](https://dotpress.dev/adapters/aws-lambda.md). ## What to deploy | Setting | Value | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | Code | the bundle of the handler, `dist/lambda.mjs` ([Bundle the handler](https://dotpress.dev/adapters/aws-lambda.md#bundle-the-handler)) | | Runtime | Node.js 22 or later | | Handler | `lambda.handler` | | Architecture | `arm64` (cheaper) or `x86_64`: the bundle works on both | | Memory | 512 MB to start: CPU grows with memory, and so does the speed of bcrypt and of cold starts | | Timeout | above your slowest route, and below the timeout of the trigger | Deploy it with your tool: AWS SAM, CDK, Serverless Framework, Terraform, SST… Dotpress does not depend on any. ## The trigger | Trigger | Payload | When | | ------------------------- | ------- | ---------------------------------------------------------------------------------------- | | API Gateway HTTP API | v2 | The default: cheaper and faster than REST APIs | | Lambda Function URL | v2 | One function, no gateway: the simplest | | API Gateway REST API | v1 | When you need its features: usage plans, API keys, AWS WAF, request validation | | Application Load Balancer | ALB | When the API shares a load balancer with other services. Enable the multi-value headers. | The handler of Dotpress accepts the four: changing the trigger does not change the code. ### Timeouts and sizes API Gateway stops a request after about 30 seconds by default (29 for REST APIs). AWS also limits the size of requests and responses. Over a limit, AWS answers `413` itself, before the function runs, in its own format rather than the [error format](https://dotpress.dev/routing/errors.md) of Dotpress: | Trigger | Largest request | Largest response | | ------------------------- | --------------------------------------------------------------------- | ---------------- | | API Gateway, Function URL | 6 MB for the whole event: about 4.5 MB of binary body, sent in base64 | 6 MB | | Application Load Balancer | 1 MB of body | 1 MB | Keep the [body limit](https://dotpress.dev/routing/bodies.md#body-size-limit) of upload routes below these, or upload large files directly to S3 with a presigned URL. ### REST APIs A REST API sends a binary response as binary only when the `Accept` header of the request matches one of its binary media types, and passes a binary request body intact only when its `Content-Type` matches. Set the binary media types to `*/*`: otherwise downloads and `stream()` responses arrive in base64. HTTP APIs, Function URLs and load balancers need no setting. | Tool | Setting | | --------- | ----------------------------------------------------------------------------------- | | AWS CDK | `binaryMediaTypes: ['*/*']` in the options of `LambdaRestApi` or `RestApi` | | AWS SAM | `BinaryMediaTypes: ['*~1*']` in the `AWS::Serverless::Api` (SAM writes `/` as `~1`) | | Terraform | `binary_media_types = ["*/*"]` in `aws_api_gateway_rest_api` | ## Configuration and secrets Pass the configuration as environment variables of the function. For secrets (the keys of the tokens, database passwords), use AWS Secrets Manager or Parameter Store, read in the factory of the handler: ```ts export const handler = createLambdaHandler(async () => { const secrets = await loadSecrets() // Secrets Manager, Parameter Store const config = loadConfig({ ...process.env, ...secrets }) return createApp({ adapter: honoAdapter(), routers, plugins: [authPlugin(createAuthService(config))] }) }) ``` The factory runs at the first invocation of each execution environment; its result is reused by the next ones. A failure, such as a secret that cannot be read, is retried at the next invocation. The AWS Parameters and Secrets Lambda Extension can cache them locally. ## Cold starts A cold start creates the execution environment, loads the bundle, and runs the factory. To keep it short: - **a small bundle**: the Hono adapter gives the smallest one (see [Choosing an adapter](https://dotpress.dev/adapters/index.md)); - **lazy imports** for the code only some routes need: `await import('./pdf.ts')` inside the handler of the route; - **a short factory**: open connections lazily rather than all at startup; - **provisioned concurrency**, for latency-sensitive APIs: environments kept ready. ## Databases Each execution environment keeps its own connections, and Lambda can run hundreds of environments at once. Size the connection pools for many small environments (one connection each is often enough), or put a proxy in front of the database: RDS Proxy, PgBouncer, or a database with an HTTP API. ## Shared state Every execution environment is a separate instance: the state must be shared, as with several servers. Use a [shared store](https://dotpress.dev/auth/passwords.md#a-shared-store) for the login throttling, Redis or DynamoDB for the cache, and SQS for the events. See [Several instances](https://dotpress.dev/deployment/node.md#several-instances). ## CORS Configure CORS either in API Gateway or the Function URL, or in Dotpress, not both: AWS answers preflight requests before the function runs, and the headers would be duplicated. See [CORS](https://dotpress.dev/routing/http-options.md#cors). ## Logs The standard output goes to CloudWatch Logs. Log JSON lines (Pino, or the default logger of Dotpress), and filter them with CloudWatch Logs Insights by `requestId`. ## Limits - **Responses are buffered**: Server-Sent Events are not supported, and `stream()` sends its body once complete. Lambda response streaming is not supported yet. - **No background work after the response**: an execution environment is frozen once the response is sent. Send the work to a queue with [events](https://dotpress.dev/services/events.md): the listeners run in another function, triggered by SQS. See [Event workers](https://dotpress.dev/deployment/event-workers.md#amazon-sqs). --- url: https://dotpress.dev/deployment/event-workers.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Event workers The listeners of [`@dotpress/events`](https://dotpress.dev/services/events.md) run in workers: processes that read a queue and run the listener of each message. This page covers where to run them, and how to set up each queue. ## Choose a queue | Queue | Transport | Workers | When | | -------------------- | ----------- | ------------------------------------------- | ------------------------------------------------------------------ | | Redis | BullMQ | a container | You already run Redis, or want the simplest queue next to a server | | Postgres | pg-boss | a container | No other infrastructure than your database | | Amazon SQS | SQS | Lambda functions, or a container | On AWS, with an API on Lambda or containers | | Cloudflare Queues | Cloudflare | Workers, or a container | On Cloudflare | | Google Cloud Pub/Sub | Pub/Sub | push endpoints (Cloud Run…), or a container | On Google Cloud | | Azure Service Bus | Service Bus | Azure Functions, or a container | On Azure | The code that emits does not change from one to another: only the transport of the bus, and the entry point of the worker. | Queue | Message size | `delay` | The same message sent again | | ----------------- | ----------------------------------------- | ------------------------------- | -------------------------------------------------------------------- | | BullMQ | — | no limit | ignored while the job exists (completed jobs are removed by default) | | pg-boss | — | no limit | ignored | | SQS | 1 MiB | 15 minutes; none on FIFO queues | ignored for 5 minutes on FIFO queues | | Cloudflare Queues | 128 KB | 24 hours | delivered again | | Pub/Sub | about 7.5 MB | not supported | delivered again | | Service Bus | 256 KB (Standard), 1 MB or more (Premium) | no limit | ignored with duplicate detection | "The same message" is a message with the same `id`: sent by `EventEmitError#retry()`, or by `emit()` with the same `emissionId`. The memory and sync transports run it again. In every case, listeners must still ignore the duplicates by `id`: see [Retries and idempotency](https://dotpress.dev/services/events.md#retries-and-idempotency). A message larger than the limit fails at `emit()`, with an `EventEmitError`; the other messages of the emission are sent. ## Rules for every queue - **Configure a dead-letter queue.** After its last attempt, a failing message goes there, where you inspect it and replay it. Dead-letter queues are part of your infrastructure (CDK, Terraform, Wrangler…): each section below gives the setting. - **Align the attempts.** Set `maxAttempts` of the worker to the retry limit of the queue: `onFailure` then reports the last attempt as `final`, for your alerts. - **Give listeners enough time.** The visibility timeout, lease or lock of a message must outlast your slowest listener, or the message is delivered again while it runs. - **Make listeners idempotent.** Every queue delivers at least once: use the message `id` to ignore duplicates. See [Retries and idempotency](https://dotpress.dev/services/events.md#retries-and-idempotency). - **Deploy workers before routing events to them.** A message for a listener its worker does not know fails as `unknown-listener`. When you rename a listener, deploy workers that know both names first. **Messages that can never be handled** (not an envelope, unknown listener, invalid payload) are `dead`: retrying would not help. When the transport can send them to the dead-letter queue directly, they go there at once; otherwise, they fail until the retry limit, like other failures. ## Long-running workers On a server or in a container, a worker is started by `dotpress-events work`, with a module that exports the `worker` and the `source` of its messages: ```sh node_modules/.bin/dotpress-events work src/worker.ts node_modules/.bin/dotpress-events work src/worker.ts --watch # development: restarts when a file changes ``` ```ts file="/../examples/events/src/worker.ts" import { createConsoleLogger } from '@dotpress/core' import { createWorker } from '@dotpress/events' import { createBullmqSource } from '@dotpress/events/bullmq' import { queueName, redisConnection } from './bus.ts' import { listeners } from './events.ts' // Entry of `dotpress-events work src/worker.ts`: reads the BullMQ queue and // runs the listeners, until Ctrl+C or SIGTERM (it then finishes the jobs in // progress). In production, run it in its own container. const redisUrl = process.env.REDIS_URL if (!redisUrl) { throw new Error( 'REDIS_URL is required: without it, the API runs the listeners itself.' ) } export const logger = createConsoleLogger({ bindings: { process: 'worker' } }) export default { worker: createWorker({ listeners, logger, // The attempts of the BullMQ jobs (3 by default): the last failure is // reported as final, for alerts. maxAttempts: 3, onFailure: (error, { envelope, attempt, final }) => { if (final) { logger.error( { error, listener: envelope?.listener, id: envelope?.id, attempt }, 'Event listener gave up: the job stays in the failed jobs' ) } }, }), source: createBullmqSource({ queue: queueName(), connection: redisConnection(redisUrl), concurrency: 5, }), logger, } ``` - **The module** exports `{ worker, source }` and optionally a `logger`, or a function returning them; `--export` chooses another export than `default`. TypeScript modules need Node.js 22.18 or later (erasable syntax, relative imports ending in `.ts`); otherwise, run the compiled module, or the command with `NODE_OPTIONS="--import tsx"`. - **Stop**: `SIGTERM` (or Ctrl+C) stops reading, and waits for the messages in progress; a second signal, a second later or more, exits at once. Repeats within one second are ignored, because `npm run`, `pnpm run` and `--watch` relay the signal they receive. Give the platform a stop delay above your slowest listener. - **Logs**: JSON lines on the standard error. - **Scale**: raise the number of messages a worker handles at once (`concurrency`, on every source), then the number of worker instances. - **In a container**: the image of the API, with another command. See [Containers](https://dotpress.dev/deployment/node.md#containers). In code, `startWorker(worker, source, { logger, signal })` does the same, and returns `{ stop() }`. Without a `logger`, the workers and the queue handlers (`createSqsHandler()` and the others below) log to the console, from the `info` level: a failing listener always leaves a trace, in CloudWatch Logs or the logs of the platform. Pass your logger, such as Pino or the Dotpress logger, to change the format or the level. ## Redis (BullMQ) ```sh npm install bullmq ioredis ``` ```ts import { createBullmqSource, createBullmqTransport } from '@dotpress/events/bullmq' const connection = { host: 'redis.internal', port: 6379 } // The API: while Redis is unreachable, emit() fails at once. const transport = createBullmqTransport({ queue: 'events', connection: { ...connection, enableOfflineQueue: false }, }) // On shutdown: await transport.close() // worker.ts: the worker waits for Redis to come back. export default { worker: createWorker({ listeners, maxAttempts: 3 }), source: createBullmqSource({ queue: 'events', connection, concurrency: 5 }), } ``` Each message becomes a [BullMQ](https://docs.bullmq.io) job named after its listener, with the message id as job id: the same message sent again adds no duplicate while the job exists. Completed jobs are removed by default (`removeOnComplete: true`): once its job has completed, the same message sent again is a new job, and runs again. - **Redis 6.2 or later, with `maxmemory-policy=noeviction`**: Redis must never evict the keys of the queue. A managed Redis often defaults to another policy: check it. - **Retries** (`jobOptions`, merged with the defaults): 3 `attempts`, an `exponential` backoff from 1 second, completed jobs removed (`removeOnComplete: true`), failed jobs kept (`removeOnFail: false`). Set `maxAttempts` to the same number. - **Dead letters**: failed jobs stay in the failed set of the queue, with their error, where a dashboard such as Bull Board shows and retries them. Messages that can never be handled fail at once, without retries (`UnrecoverableError`). - **The source** handles `concurrency` jobs at a time (1 by default). On stop, it waits for the jobs in progress, up to `closeTimeout` (30 seconds by default); their jobs then become stalled, and another worker retries them. While Redis is unreachable, BullMQ cannot close: the stop gives up after `closeTimeout`. - **Redis outages**: with `enableOfflineQueue: false`, the transport fails at once while Redis is unreachable, and `emit()` throws an `EventEmitError` that `retry()` sends again. Without it, ioredis keeps the commands until Redis comes back, and `emit()` waits up to the `sendTimeout` of the bus (10 seconds by default). The source waits for Redis and resumes on its own. - **Connection**: use the `prefix` option for the key prefix, not the `keyPrefix` of ioredis. The source needs `maxRetriesPerRequest: null`: BullMQ sets it for connection options, and an ioredis instance passed to the source must have it. The transport does not: with `null`, its commands would wait for Redis without limit. Pass `queue` instead of `name` and `connection` to reuse a BullMQ `Queue`. - BullMQ runs on Node.js and Bun. For development, the [Events example](https://dotpress.dev/examples/events.md) starts Redis with Docker Compose: ```yaml file="/../examples/events/compose.yaml" # Redis for the BullMQ queue: docker compose up -d services: redis: image: redis:7-alpine # BullMQ requires that Redis never evicts its keys. command: redis-server --maxmemory-policy noeviction ports: - '6379:6379' ``` ## Postgres (pg-boss) ```sh npm install pg-boss ``` ```ts import { createPgBossSource, createPgBossTransport } from '@dotpress/events/pg-boss' const boss = process.env.DATABASE_URL! // or pg-boss options, or a started instance const queueOptions = { deadLetter: 'events-dlq' } // The API const transport = createPgBossTransport({ boss, queue: 'events', queueOptions }) // On shutdown: await transport.close() // worker.ts export default { worker: createWorker({ listeners, maxAttempts: 3 }), source: createPgBossSource({ boss, queue: 'events', queueOptions, concurrency: 5 }), } ``` [pg-boss](https://pgboss.io) keeps the queue in your Postgres database (13 or later), and needs Node.js 22.12 or later, or Bun. With a connection string or options, the transport and the source start their own pg-boss instance (`close()` stops the one of the transport); pass a started instance to share it. - **Queues** are created on first use, with `queueOptions` merged with the defaults: 3 attempts (`retryLimit: 2`), an exponential backoff from 1 second (`retryDelay: 1`, `retryBackoff: true`). Existing queues are not changed. Set `maxAttempts` to `retryLimit + 1`. - **Dead letters**: with `deadLetter`, the dead-letter queue is created too. Failed jobs go there after their last attempt, and messages that can never be handled at once. - **Duplicates**: the job id is the message id: the same message sent again is ignored. - **The source** handles `concurrency` jobs at a time (1 by default), in parallel, each with its own result: one failure does not retry the others. `pollInterval` sets the wait on an empty queue (half a second at least). On stop, it waits for the jobs in progress, up to `closeTimeout` (30 seconds by default). ## Amazon SQS ```sh npm install @aws-sdk/client-sqs ``` ```ts import { createSqsTransport } from '@dotpress/events/aws-sqs' const transport = createSqsTransport({ queueUrl: process.env.EVENTS_QUEUE_URL! }) ``` Messages are sent in batches of 10 (`SendMessageBatch`), with `event` and `listener` message attributes. The client comes from the environment (region, credentials), or from `clientConfig`; pass `client` to reuse yours. **FIFO queues** (URL ending with `.fifo`) keep the order within a message group: the listener by default, or `messageGroupId: (envelope) => …` to group by entity. They deduplicate messages by id for 5 minutes, and do not accept delays. ### Lambda workers ```ts import { createSqsHandler } from '@dotpress/events/aws-sqs' export const handler = createSqsHandler(createWorker({ listeners, logger, maxAttempts: 5 }), { deadLetter: process.env.EVENTS_DLQ_URL, // optional, see below retryDelay: (attempt) => 30 * 2 ** (attempt - 1), // optional backoff, in seconds or like '30s' }) ``` The messages of a batch run in parallel; on a FIFO queue, in order, stopping at the first failure. Configure the queue and its trigger: - **`ReportBatchItemFailures`** on the event source mapping: the handler returns the failed messages, and only they are retried. Without it, one failure retries the whole batch. - **A dead-letter queue**, with a redrive policy: `maxReceiveCount` is the number of attempts. Set `maxAttempts` to the same value. - **A visibility timeout** of at least 6 times the timeout of the function (AWS recommendation). A failed message becomes visible again after it; `retryDelay(attempt)` sets another delay (`ChangeMessageVisibility`, up to 12 hours). - With `deadLetter`, the URL of the dead-letter queue, messages that can never be handled are copied to the dead-letter queue at once, with `reason` and `error` attributes, instead of failing until `maxReceiveCount`. ```ts // AWS CDK const dlq = new sqs.Queue(this, 'EventsDlq', { retentionPeriod: Duration.days(14) }) const queue = new sqs.Queue(this, 'Events', { visibilityTimeout: Duration.seconds(180), // 6 × the timeout of the function deadLetterQueue: { queue: dlq, maxReceiveCount: 5 }, }) worker.addEventSource(new SqsEventSource(queue, { batchSize: 10, reportBatchItemFailures: true })) ``` ```hcl # Terraform resource "aws_sqs_queue" "events_dlq" { name = "events-dlq" message_retention_seconds = 1209600 } resource "aws_sqs_queue" "events" { name = "events" visibility_timeout_seconds = 180 redrive_policy = jsonencode({ deadLetterTargetArn = aws_sqs_queue.events_dlq.arn maxReceiveCount = 5 }) } resource "aws_lambda_event_source_mapping" "events" { event_source_arn = aws_sqs_queue.events.arn function_name = aws_lambda_function.worker.arn batch_size = 10 function_response_types = ["ReportBatchItemFailures"] } ``` **IAM permissions**: `sqs:SendMessage` for the code that emits. For workers, `sqs:ReceiveMessage`, `sqs:DeleteMessage` and `sqs:GetQueueAttributes` (granted by the event source mapping on Lambda); `sqs:ChangeMessageVisibility` with `retryDelay` or `visibilityTimeout`; `sqs:SendMessage` on the dead-letter queue with `deadLetterQueueUrl`. ### Long-running workers ```ts import { createSqsSource } from '@dotpress/events/aws-sqs' export default { worker: createWorker({ listeners, maxAttempts: 5 }), source: createSqsSource({ queueUrl: process.env.EVENTS_QUEUE_URL!, visibilityTimeout: 60 }), } ``` The source reads the queue by long polling (`waitTime`, 20 seconds by default; `concurrency`, 10 messages by default), runs the messages of a batch in parallel, and deletes the handled ones. With `visibilityTimeout`, it extends the visibility of a message while its listener runs, every half timeout. Receive errors are logged and retried, after 1 second, then up to 30 seconds. At startup, it warns when the queue has no dead-letter queue. During development, `dotpress-events work` reads your development queue as the Lambda would, without deploying. ## Cloudflare Queues No dependency: the transport uses the binding of the queue inside Workers, and `fetch` elsewhere. ```jsonc // wrangler.jsonc { "queues": { "producers": [{ "queue": "events", "binding": "EVENTS_QUEUE" }], "consumers": [ { "queue": "events", "max_batch_size": 10, "max_retries": 5, "dead_letter_queue": "events-dlq" } ] } } ``` ```ts import { createCloudflareQueueTransport } from '@dotpress/events/cloudflare-queues' // Sending, inside a Worker: the producer binding const workerTransport = createCloudflareQueueTransport({ queue: () => env.EVENTS_QUEUE }) // Sending from elsewhere (Node.js, Lambda…): the REST API const restTransport = createCloudflareQueueTransport({ accountId: process.env.CF_ACCOUNT_ID!, queueId: process.env.CF_QUEUE_ID!, // the ID of the queue, not its name apiToken: process.env.CF_API_TOKEN!, // Queues Write permission }) ``` `queue` also accepts the binding itself. Messages are sent as JSON, in batches of 100 messages and 256 KB at most; a message is limited to 128 KB, including about 100 bytes of metadata. ### Worker consumers ```ts import { createCloudflareQueueHandler } from '@dotpress/events/cloudflare-queues' export default { queue: createCloudflareQueueHandler(createWorker({ listeners, maxAttempts: 6 }), { retryDelay: (attempt) => 30 * attempt, // optional, in seconds or like '30s' deadLetter: () => env.EVENTS_DLQ, // optional producer binding, see below }), } ``` Each message is acknowledged or retried on its own: a failure does not retry the whole batch. After `max_retries`, Cloudflare moves the message to the `dead_letter_queue` of the consumer; without one, the message is deleted. Set `maxAttempts` to `max_retries + 1`. With `deadLetterQueue`, a producer binding to the dead-letter queue, messages that can never be handled are sent there at once. ### Pull consumers To run the workers outside Cloudflare (a container, your machine with `dotpress-events work`), enable an HTTP pull consumer on the queue: `wrangler queues consumer http add events`. A queue has either a Worker consumer or a pull consumer. ```ts import { createCloudflareQueueSource } from '@dotpress/events/cloudflare-queues' export default { worker: createWorker({ listeners, maxAttempts: 6 }), source: createCloudflareQueueSource({ accountId, queueId, apiToken, // Queues Read and Write permissions visibilityTimeout: '1m', // the lease: longer than your slowest listener deadLetter: deadLetterQueueId, // optional: dead messages are pushed there at once }), } ``` The source pulls `concurrency` messages (10 by default, up to 100), runs them in parallel, then acknowledges or retries them in one request. The API cannot extend a lease: set `visibilityTimeout` (30 seconds by default, up to 12 hours) above your slowest listener. An empty queue is pulled again after `pollInterval` (1 second by default). Errors are logged and retried, after 1 second, then up to 30 seconds. ## Google Cloud Pub/Sub ```sh npm install google-auth-library # to publish with Application Default Credentials npm install jose # push endpoints: to verify the tokens npm install @google-cloud/pubsub # pull workers ``` Each one is optional: install what you use. ```ts import { createPubSubTransport } from '@dotpress/events/google-pubsub' const transport = createPubSubTransport({ topic: 'projects/my-project/topics/events' }) ``` The transport publishes over the REST API, with `fetch`: it runs on Node.js, Bun, Deno and Cloudflare Workers. Each message carries the attributes `event` and `listener`: a subscription can filter on them (`--message-filter='attributes.listener = "send-welcome-mail"'`) to run some listeners on other workers. - **Authentication**: an OAuth token from Application Default Credentials, through `google-auth-library` (the service account of Cloud Run, GKE or Cloud Functions, `GOOGLE_APPLICATION_CREDENTIALS`, or `gcloud auth application-default login`). The account needs the Pub/Sub Publisher role (`roles/pubsub.publisher`) on the topic. Elsewhere, pass `getAccessToken`, which returns a token with the `https://www.googleapis.com/auth/pubsub` scope. For the emulator: `baseUrl: 'http://localhost:8085', getAccessToken: false`. - **Limits**: 10 MB and 1,000 messages per request (larger emissions are split); 10 MB per message with its base64-encoded envelope, about 7.5 MB of JSON. Pub/Sub does not support delays: an emission with a `delay` fails. ### Subscriptions and dead letters ```sh gcloud pubsub topics create events gcloud pubsub topics create events-dlq gcloud pubsub subscriptions create events-worker --topic=events \ --ack-deadline=60 --min-retry-delay=10s --max-retry-delay=600s \ --dead-letter-topic=events-dlq --max-delivery-attempts=5 ``` With a dead-letter policy, Pub/Sub counts the delivery attempts, and moves a message to the dead-letter topic after `--max-delivery-attempts` (5 to 100); its service account needs the Publisher role on the dead-letter topic and the Subscriber role on the subscription. Set `maxAttempts` to `--max-delivery-attempts`. Without a dead-letter policy, every delivery counts as the first attempt, and a failing message is delivered again until the retention of the subscription expires (7 days by default). With the `deadLetter` option (`{ topic }`) of the push handler or of the pull source, messages that can never be handled are published at once to that topic, with the attributes `reason` and `error`. ### Push endpoints A push subscription POSTs each message to your endpoint, with an OIDC token signed by Google: ```sh gcloud pubsub subscriptions create events-push --topic=events \ --push-endpoint=https://api.example.com/pubsub \ --push-auth-service-account=pubsub-push@my-project.iam.gserviceaccount.com \ --ack-deadline=60 --dead-letter-topic=events-dlq --max-delivery-attempts=5 ``` ```ts import { createPubSubHandler } from '@dotpress/events/google-pubsub' const push = createPubSubHandler(createWorker({ listeners, maxAttempts: 5 }), { audience: 'https://api.example.com/pubsub', // the push endpoint, or --push-auth-token-audience serviceAccountEmail: 'pubsub-push@my-project.iam.gserviceaccount.com', deadLetter: { topic: 'projects/my-project/topics/events-dlq' }, // optional }) // Web-standard runtimes (Hono, Cloudflare Workers, Bun, Deno) app.post('/pubsub', (c) => push.fetch(c.req.raw)) // Other frameworks: the parsed JSON body and the Authorization header app.post('/pubsub', async (req, res) => { res.status(await push.handle(req.body, req.headers.authorization)).end() }) ``` The handler verifies the token with `jose`: the signature with the keys of Google, the issuer, the `audience`, a verified `email`, equal to `serviceAccountEmail` when set. It answers `204` when the message is handled (or moved to `deadLetter`), `503` to have it delivered again, `401` and `403` for invalid tokens, `400` for bodies that are not push messages. Set `verifyToken: false` only behind a proxy that checks the token. Pub/Sub waits up to the ack deadline of the subscription (10 seconds by default, up to 600): set it above your slowest listener. ### Pull workers ```ts import { createPubSubSource } from '@dotpress/events/google-pubsub' export default { worker: createWorker({ listeners, maxAttempts: 5 }), source: createPubSubSource({ subscription: 'projects/my-project/subscriptions/events-worker', concurrency: 10, // messages handled at once (the default) deadLetter: { topic: 'projects/my-project/topics/events-dlq' }, // optional }), } ``` The source uses the streaming pull of `@google-cloud/pubsub` (Node.js), which extends the ack deadline of the messages in progress. Credentials come from Application Default Credentials, `clientConfig` (options of `new PubSub()`), or the `client` you pass; the emulator is used when `PUBSUB_EMULATOR_HOST` is set. On stop, the source waits for the messages in progress, up to `closeTimeout` (30 seconds by default). ## Azure Service Bus ```sh npm install @azure/service-bus ``` ```ts import { createServiceBusSource, createServiceBusTransport } from '@dotpress/events/azure-service-bus' const connection = { connectionString: process.env.SERVICE_BUS_CONNECTION! } // Or Microsoft Entra ID: // const connection = { client: new ServiceBusClient('my-namespace.servicebus.windows.net', new DefaultAzureCredential()) } // The API const transport = createServiceBusTransport({ ...connection, queue: 'events' }) // On shutdown: await transport.close() // worker.ts export default { worker: createWorker({ listeners, maxAttempts: 10 }), // the maxDeliveryCount of the queue source: createServiceBusSource({ ...connection, queue: 'events', concurrency: 4 }), } ``` The SDK speaks AMQP: Node.js only. With a connection string, the transport and the source create their own client (`close()` closes the one of the transport); pass a `client` to share it, or to use Microsoft Entra ID (`@azure/identity`, with the Azure Service Bus Data Sender or Data Receiver role). - **Messages** carry the envelope as JSON, `subject` (the event) and the application properties `event` and `listener`. The `messageId` is the message id: with duplicate detection on the queue (`requiresDuplicateDetection`, set when the queue is created; Standard and Premium tiers), the same message sent again within the detection window is ignored. `delay` schedules the message (`scheduledEnqueueTimeUtc`). - **Limits**: 256 KB per message in the Standard tier, properties included; in the Premium tier, 1 MB unless raised on the queue (up to 100 MB). Batches are filled up to the size the queue accepts, 1 MB at most. - **The source** handles `concurrency` messages at a time (1 by default), in peek-lock mode. The lock of a message in progress is renewed for `maxLockRenewal` (5 minutes by default; the lock itself lasts 1 minute by default, 5 at most). A failed message is abandoned: Service Bus delivers it again at once, until the `maxDeliveryCount` of the queue (10 by default), then moves it to the dead-letter queue. Messages that can never be handled go there at once, with a `deadLetterReason` (`invalid-envelope`, `unknown-listener`, `invalid-payload`). On stop, the source waits for the messages in progress, up to `closeTimeout` (30 seconds by default). Service Bus does not wait between attempts: a listener that calls a service which is down fails its attempts within seconds. Keep `maxDeliveryCount` high enough, and retry short outages inside the listener. ### Azure Functions ```ts import { app } from '@azure/functions' import { createServiceBusHandler } from '@dotpress/events/azure-service-bus' app.serviceBusQueue('events', { connection: 'SERVICE_BUS_CONNECTION', queueName: 'events', handler: createServiceBusHandler(createWorker({ listeners, maxAttempts: 10 }), { // optional, see below deadLetter: { connectionString: process.env.SERVICE_BUS_CONNECTION!, queue: 'events-failed' }, }), }) ``` The handler takes one message per invocation (`cardinality: 'one'`, the default). A failure throws: the Functions host abandons the message, delivered again until `maxDeliveryCount`, then moved to the dead-letter queue. `attempt` is the `deliveryCount` of the trigger metadata. A function cannot move a message to the dead-letter queue itself: with `deadLetter`, messages that can never be handled are sent to that queue, with the properties `reason` and `error`, and the invocation succeeds. ## Monitoring - **`onFailure`** on the worker receives each failure, with `final` on the last attempt: raise an alert on final failures. - **Logs**: `Event listener failed, the message is retried` (warn), `Event listener failed, the message is not retried` (error). Payloads are never logged. See [the logs](https://dotpress.dev/reference/events.md#logs). - **Dead-letter queues**: watch their size. A growing dead-letter queue is a bug, or a service down. --- url: https://dotpress.dev/deployment/node.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Node.js and containers A Dotpress app on Node.js is a long-running process: a container, a VM, or a platform that runs one (Cloud Run, Fly.io, Railway, Render, Kubernetes…). This page covers what to set up before going to production. ## Run TypeScript Node.js 22.18 or later runs TypeScript files directly: `node src/server.ts`, without a build step. The examples run this way in production too. Node.js only strips the types, so the code must use erasable syntax only, and relative imports end with `.ts` (see [Installation](https://dotpress.dev/getting-started/installation.md#configure-typescript)). You can also compile with `tsc` or a bundler, and run the JavaScript: Dotpress works the same. ## Configuration Dotpress never reads environment variables: the configuration is yours. Read it once, at startup, and check it with Zod: a missing or invalid variable stops the process with an explicit message, instead of failing later on a request. ```ts file="/../examples/tasks-api/src/config.ts" import { z } from 'zod' // Every setting of the app, from the environment, checked at startup: a // missing or invalid variable stops the process with an explicit message, // instead of failing later on a request. const Env = z.object({ NODE_ENV: z .enum(['development', 'test', 'production']) .default('development'), PORT: z.coerce.number().int().min(0).max(65_535).default(3000), /** SQLite database file, created when missing. */ DATABASE_PATH: z.string().min(1).default('data/tasks.db'), /** Public URL of the API, written in the tokens (`iss`). */ PUBLIC_URL: z.url().optional(), /** RSA key pair (PEM); generated in `data/` in development. */ JWT_PRIVATE_KEY: z.string().min(1).optional(), JWT_PUBLIC_KEY: z.string().min(1).optional(), /** * Redis: the queue of the events (BullMQ) and a shared cache. Without * it, the listeners run in the API process, and the cache lives in * memory. */ REDIS_URL: z.url().optional(), /** Name of the BullMQ queue, shared by the API and the worker. */ EVENTS_QUEUE: z.string().min(1).default('tasks-api-events'), /** SMTP server of the emails. Without it, they are printed. */ SMTP_URL: z.url().optional(), MAIL_FROM: z.string().min(1).default('Tasks '), }) export type Config = ReturnType /** Reads the configuration, or throws an error listing the problems. */ export const loadConfig = ( env: Record = process.env ) => { const result = Env.safeParse(env) if (!result.success) { throw new Error(`Invalid configuration:\n${z.prettifyError(result.error)}`) } const config = result.data return { ...config, production: config.NODE_ENV === 'production', publicUrl: config.PUBLIC_URL ?? `http://localhost:${config.PORT}`, } } /** * Checks the variables a process needs in production: the API and the * worker do not need the same ones. */ export const requireInProduction = ( config: Config, names: readonly (keyof Config & Uppercase)[] ) => { const missing = names.filter((name) => !config[name]) if (config.production && missing.length > 0) { throw new Error(`Required in production: ${missing.join(', ')}.`) } } ``` Each process declares what it needs in production: the API needs the keys of the tokens, the worker does not. ```ts const config = loadConfig() requireInProduction(config, ['PUBLIC_URL', 'JWT_PRIVATE_KEY', 'JWT_PUBLIC_KEY']) ``` Keep the secrets (keys, passwords, tokens) in the secret manager of your platform, given to the process as environment variables. Never in the image, never in the repository. ## Graceful shutdown Platforms stop a container with `SIGTERM`, then kill it after a delay (10 seconds for Docker, 30 for Kubernetes). On `SIGTERM`, call `app.close()`: it stops accepting connections, waits for the pending requests, closes the streamed responses, then runs the `onClose` hooks of the plugins. Close your own connections afterwards. ```ts file="/../examples/tasks-api/src/http/server.ts" // Entry point of the API: config → services → app → listen. import { fastifyAdapter } from '@dotpress/adapter-fastify' import { createConsoleLogger } from '@dotpress/core' import { loadConfig, requireInProduction } from '../config.ts' import { openDatabase } from '../db/database.ts' import { loadKeys } from '../features/auth/keys.ts' import { createNotifications } from '../features/notifications/listeners.ts' import { createBus, createTransport } from '../services/bus.ts' import { createCacheStore } from '../services/cache-store.ts' import { createRepositories } from '../services/index.ts' import { createAppMailer, createMailProvider } from '../services/mailer.ts' import { createTasksApp } from './app.ts' const config = loadConfig() requireInProduction(config, [ 'PUBLIC_URL', 'JWT_PRIVATE_KEY', 'JWT_PUBLIC_KEY', // Without Redis, the API sends the emails itself. ...(config.REDIS_URL ? [] : (['SMTP_URL'] as const)), ]) const logger = createConsoleLogger() // The services of this process, created once, closed on shutdown. const repositories = createRepositories(openDatabase(config.DATABASE_PATH)) const cacheStore = await createCacheStore(config.REDIS_URL) const mailProvider = createMailProvider(config) const transport = createTransport(config) if (transport.kind === 'memory') { logger.info('REDIS_URL is not set: the listeners run in this process') } else if (mailProvider.name === 'console') { logger.info('SMTP_URL is not set: the worker prints the emails') } const app = await createTasksApp({ adapter: fastifyAdapter(), repositories, keys: loadKeys(config), publicUrl: config.publicUrl, cacheStore: cacheStore.store, // The bus routes each event to its listeners, by name: with BullMQ, the // worker runs them; without, the in-memory queue of this process. events: createBus( transport, createNotifications({ repositories, mailer: createAppMailer(mailProvider, config.MAIL_FROM), }), { logger } ), logger, }) await app.listen(config.PORT) logger.info(`Tasks API: ${config.publicUrl}`) logger.info(`API reference: ${config.publicUrl}/docs`) // Waits for pending requests, then closes the connections. for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, () => { // eventsPlugin closes the transports of the bus with the app. void app .close() .then(() => cacheStore.close()) .then(() => { mailProvider.close?.() repositories.db.close() }) }) } ``` Without it, a deployment cuts the requests in progress. ## Health checks Give the platform a route to check that the app is alive, and that it can reach its database: ```ts const healthRouter = createRouter() healthRouter.defineRoute({ path: '/health', meta: { summary: 'Health check', tags: ['health'] }, handler: ({ services }) => { services.db.prepare('SELECT 1').get() return { status: 'ok' } }, }) ``` A failing check returns a `500`, and the platform stops sending traffic to the instance. Keep it cheap: it runs every few seconds. ## Behind a proxy In production, a load balancer or a reverse proxy usually sits in front of the app, and terminates HTTPS: - **Client IP addresses**: configure the server to trust the proxy headers, or every client shares the address of the proxy, including in the login throttling. See [Client IP address](https://dotpress.dev/routing/http-options.md#client-ip-address-behind-a-proxy). - **Sub-path**: when the app is served under a prefix (`/api`), use `basePath` or `publicBasePath`. See [Base path](https://dotpress.dev/routing/http-options.md#base-path). - **Request IDs**: to keep the ID set by the proxy, use `generateRequestId`. See [Request IDs](https://dotpress.dev/routing/logging.md#request-ids). - **Timeouts**: the proxy closes slow requests (often after 60 seconds), and idle connections. Server-Sent Events send a heartbeat every 15 seconds to stay open. ## Logs Write the logs to the standard output, as JSON, and let the platform collect them. [Pino](https://getpino.io) does it, and works as is with Dotpress: ```ts import pino from 'pino' const app = await createApp({ adapter, logger: pino() }) ``` Each line of a request carries its `requestId`, also sent to the client in `X-Request-ID`. See [Logging](https://dotpress.dev/routing/logging.md). ## Several instances With several instances behind a load balancer, keep every state in shared services: | State | In memory, per instance | Shared | | ---------------- | ------------------------- | ----------------------------------------------------------------------------------------- | | Sessions | — | the refresh tokens, in your database | | Login throttling | the default store | a [shared store](https://dotpress.dev/auth/passwords.md#a-shared-store) (Redis, Postgres) | | Cache | `createMemoryStore()` | `createRedisStore()`: an invalidation must reach every instance | | Event queue | `createMemoryTransport()` | BullMQ, SQS, pg-boss… | | Revoked sessions | — | `isSessionRevoked`, on the database or Redis | ## Containers A Dockerfile for an app that runs its TypeScript sources: ```dockerfile title="Dockerfile" FROM node:24-slim WORKDIR /app ENV NODE_ENV=production # Dependencies first: this layer is rebuilt only when they change. COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY src ./src USER node EXPOSE 3000 CMD ["node", "src/server.ts"] ``` ```text title=".dockerignore" node_modules .env* test *.log ``` - **`npm ci`** installs the exact versions of the lockfile; `--omit=dev` leaves the test tools out. - **`USER node`**: the process does not run as root. - **`CMD ["node", …]`** in the exec form: Node.js receives `SIGTERM` directly, and the app closes gracefully. Run `node` rather than `npm start`: one process less between the platform and your app. - Pick the current LTS release of Node.js for the image. An [event worker](https://dotpress.dev/deployment/event-workers.md) can use the same image, with another command: `CMD ["node_modules/.bin/dotpress-events", "work", "src/worker.ts"]`. ## Before going to production - [ ] The configuration is checked at startup, and the secrets come from a secret manager. - [ ] `SIGTERM` closes the app gracefully. - [ ] A health check route is configured on the platform. - [ ] The server trusts the proxy headers, and only those of your proxy. - [ ] Logs are JSON, on the standard output. - [ ] State is shared between the instances. - [ ] `exposeErrors` is disabled, and unexpected errors are reported with `onError`. - [ ] The [security checklist](https://dotpress.dev/auth/security.md) of the authentication is done. --- url: https://dotpress.dev/index.md --- > For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt. # Dotpress End-to-end typed backend APIs > A lightweight, decorator-free TypeScript framework. Your schemas type each request and its response, on the HTTP server you choose. [Get started](/getting-started/introduction) | [Examples](/examples/) ## Features - 🔷 **Typed from end to end**: Zod schemas validate and type the params, the query, the body and the response of each route. The OpenAPI document comes from the same routes. - ↩️ **Errors are returned**: Handlers return their errors like any other value. Every error, from a failed validation to an unexpected exception, has the same JSON format. - 🔌 **Any HTTP server**: The core knows no HTTP server. The same app runs on Express, Fastify or Hono, and on AWS Lambda. - 📦 **Packages when you need them**: Authentication, OpenAPI, emails, events, cache and testing helpers, each in its own package.