` convention that `npm create arcton` / `pnpm create arcton` / `bun create arcton` rely on, by re-exporting the same implementation.
**Example**
```bash
bunx arcton create my-app
```
```bash
cd my-app
bun install
bun run dev
```
## Templates [#templates]
Two runtime templates are available; both scaffold a project depending on `@arcton/core`.
### Bun template [#bun-template]
`package.json` scripts:
```json
{
"scripts": {
"dev": "bun --hot src/index.ts",
"start": "bun run src/index.ts",
"compile": "bun build --compile --minify --sourcemap ./src/index.ts --outfile arcton-app"
}
}
```
`src/index.ts`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen()
```
### Node template [#node-template]
`package.json` scripts:
```json
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc --build",
"start": "node dist/index.js"
}
}
```
`src/index.ts`:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen({ adapter: nodeAdapter })
```
See [Installation](../getting-started/installation.mdx) for prerequisites and [Development](../getting-started/development.mdx) for running these scripts day to day.
# Context (/en/docs/api/context)
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => {
return { id: ctx.params.id, page: ctx.query.page ?? '1' }
})
app.listen()
```
Every handler, [provider](../providers/overview.mdx), and [middleware](../middleware/overview.mdx) function receives a `Context` as its first argument (middleware also gets a `next`). This page is the type reference; see [Context](../fundamentals/context.mdx) for the concept-first guide.
## Context [#context]
**Purpose:** the full shape of `ctx` at a given point in the pipeline.
**Signature**
```ts
import type { BaseContext, QueryParams, RouteParams } from '@arcton/contracts'
type Context =
BaseContext
& TBody & TProvided
```
**Parameters**
**Behavior:** provided values sit flat on `ctx` — there is no namespace. `params` is inferred from the route literal passed to `get`/`post`/etc.: `'/users/:id'` gives `{ id: string }`, a route with no params gives `Record`, and a path passed as a non-literal `string` variable gives `Record`. `query` is `Record` by default, built lazily on first access — repeated keys keep the last value, and a key with no value reads as `''`.
## BaseContext [#basecontext]
**Purpose:** the fields present on every `Context`, regardless of what's been provided or validated.
**Signature**
```ts
import type { ResponseContext } from '@arcton/contracts'
interface BaseContext {
request: Request
params: P
query: Q
response: ResponseContext
}
```
**Behavior:** `request` is the raw, unmodified `Request`. `response` is described below.
## ResponseContext [#responsecontext]
**Purpose:** the mutable response state available before a body finalizes.
**Signature**
```ts
interface ResponseContext {
status?: number
headers: Headers
}
```
**Behavior:** `ctx.response` starts out as this plain object and is materialized into a real `Response` the moment a body finalizes at any layer (the handler returns, a step short-circuits, or a layer replaces the body after `next()`). Before materialization, `ctx.response.status` can be assigned directly. After materialization, header mutation still works and reaches the client, but `status` no longer accepts assignment. See [Response](../fundamentals/response.mdx).
Set `ctx.response.status` from the handler, or from middleware before calling `await next()`. Setting it afterward throws, because by then the body has already materialized into a real `Response`.
## RouteParams [#routeparams]
**Purpose:** the default shape of `ctx.params` for a route with no params schema.
**Signature**
```ts
type RouteParams = Record
```
## QueryParams [#queryparams]
**Purpose:** the default shape of `ctx.query` for a route with no query schema.
**Signature**
```ts
type QueryParams = Record
```
## Body [#body]
**Purpose:** the union of values a handler or middleware may return.
**Signature**
```ts
type Body =
| object
| string
| ArrayBufferView
| ArrayBuffer
| Blob
| FormData
| URLSearchParams
| ReadableStream
| Response
```
**Behavior:** each variant maps to a different HTTP response — see [Response](../fundamentals/response.mdx) for the full mapping table, including how status and headers are derived for each case.
# CORS (/en/docs/api/cors)
## Overview [#overview]
Add CORS headers and handle preflight requests with one global middleware:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: ['https://app.example.com'],
credentials: true
})
)
app.get('/', () => ({ hello: 'world' }))
app.listen()
```
Because `cors()` returns unscoped global middleware, it also covers `404`/`405` responses (see [Global middleware](../middleware/global.mdx)).
## `cors()` [#cors]
**Purpose** — builds a CORS middleware from a set of options.
**Signature**
```ts no-check
function cors(options?: CorsOptions): Middleware
```
**Parameters**
| Parameter | Type | Description |
| --------- | ------------- | -------------------------------------------- |
| `options` | `CorsOptions` | Optional. See below for fields and defaults. |
**Return type** — a [`Middleware`](./middleware-types.mdx), meant to be passed to `app.use()`.
**Errors** — throws a `TypeError` at setup — not per-request — when `origin` is `'*'` (its default) and `credentials` is `true`:
```
CORS: credentials cannot be enabled when origin is "*"
```
A credentialed response can't use the wildcard origin; the browser rejects it.
**Behavior**
* A request with no `Origin` header passes straight through — it isn't a CORS request.
* A non-wildcard allowed origin is echoed back verbatim in `Access-Control-Allow-Origin`, and `Vary: Origin` is appended.
* A disallowed origin: the request continues normally and no CORS headers are added — Arcton doesn't block it server-side; the browser enforces CORS policy client-side.
* A real preflight (an `OPTIONS` request carrying `Access-Control-Request-Method`) short-circuits with `204` and the computed CORS headers. With `methods`/`allowedHeaders` omitted, the response echoes back the request's own `Access-Control-Request-Method` / `Access-Control-Request-Headers`.
* `preflight: false` disables the automatic `204` short-circuit — a real preflight then reaches `next()` like any other request — but CORS headers are still added to whatever the route eventually returns.
* `credentials: true` adds `Access-Control-Allow-Credentials: true`.
* A non-empty `exposedHeaders` sets `Access-Control-Expose-Headers`, joined with `, `.
## `CorsOptions` [#corsoptions]
**Purpose** — the options object accepted by `cors()`.
**Signature**
```ts no-check
interface CorsOptions {
origin?: CorsOrigin
methods?: string[]
allowedHeaders?: string[]
exposedHeaders?: string[]
credentials?: boolean
maxAge?: number
preflight?: boolean
}
```
**Fields**
| Field | Type | Default | Description |
| ---------------- | ------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `origin` | `CorsOrigin` | `'*'` | Which origins are allowed. See `CorsOrigin` below. |
| `methods` | `string[]` | — | Sent as `Access-Control-Allow-Methods` on a preflight. When omitted, the preflight echoes the request's own `Access-Control-Request-Method`. |
| `allowedHeaders` | `string[]` | — | Sent as `Access-Control-Allow-Headers` on a preflight. When omitted, the preflight echoes the request's own `Access-Control-Request-Headers`. |
| `exposedHeaders` | `string[]` | — | Sent as `Access-Control-Expose-Headers` on the actual response. |
| `credentials` | `boolean` | `false` | Adds `Access-Control-Allow-Credentials: true`. Cannot be combined with `origin: '*'`. |
| `maxAge` | `number` | — | Sent as `Access-Control-Max-Age` on a preflight. |
| `preflight` | `boolean` | `true` | Whether a real preflight is automatically answered with `204`. |
## `CorsOrigin` [#corsorigin]
**Purpose** — the shape `CorsOptions.origin` accepts.
**Signature**
```ts
type CorsOrigin =
| '*'
| string
| string[]
| ((origin: string, request: Request) => boolean)
```
**Behavior** — `'*'` allows any origin (and cannot be combined with `credentials: true`). A `string` allows exactly that origin. A `string[]` allows any origin in the list. A function receives the request's `Origin` header value and the `Request` itself, and returns whether it's allowed — evaluated per request.
**Example**
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: (origin, request) =>
origin.endsWith('.example.com') || request.headers.has('x-internal')
})
)
app.get('/status', () => ({ ok: true }))
app.listen()
```
# HTTP Errors (/en/docs/api/http-errors)
## Overview [#overview]
Throw a ready-made error instead of hand-rolling `ctx.response.status = ...; return {...}` at every place a request can fail:
```ts
import { Arcton, Http } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.listen()
```
On its own this is still an uncaught error — turning it into a response is on you, the same way as any other throw. See [Responding with errors](../errors/responding-with-errors.mdx#throw-a-ready-made-httperror-instead-of-hand-rolling-one) for the try/catch pattern that maps `HttpError`'s `status`/`code`/`body` onto `ctx.response`.
## `HttpError` [#httperror]
**Purpose** — the error class every `Http` factory below returns; construct it directly for a status with no named factory.
**Signature**
```ts no-check
class HttpError extends Error {
constructor(status: number, code: string, message: string, body?: unknown)
readonly status: number
readonly code: string
readonly body?: unknown
}
```
**Parameters**
| Parameter | Type | Description |
| --------- | --------- | ------------------------------------------------------------------------------------------------------------------------- |
| `status` | `number` | The HTTP status code, e.g. `451`. |
| `code` | `string` | A stable, machine-readable tag, e.g. `'UNAVAILABLE_FOR_LEGAL_REASONS'`. Safe for a client to switch on, unlike `message`. |
| `message` | `string` | Passed to `Error`'s own `message`. |
| `body` | `unknown` | Optional. The exact value a catch handler should send back instead of a default `{ code, message }` shape. |
**Behavior** — `HttpError` carries these fields but does nothing with them by itself; nothing in Arcton's pipeline catches an `HttpError` automatically (see [Uncaught errors](../errors/uncaught-errors.mdx)).
**Example**
```ts
import { HttpError } from '@arcton/core'
throw new HttpError(451, 'UNAVAILABLE_FOR_LEGAL_REASONS', 'Unavailable For Legal Reasons')
```
## `Http` [#http]
**Purpose** — a namespace of ready-to-throw shortcuts, one per common status. Each one is a plain function — call it, don't `new` it — and returns an `HttpError`.
**Signature**
```ts no-check
type StatusErrorFactory = (message?: string, body?: unknown) => HttpError
const Http: Record
```
**Parameters**
| Parameter | Type | Description |
| --------- | --------- | ---------------------------------------------------------------------------------------------------------- |
| `message` | `string` | Optional. Defaults to the status's reason phrase (see the table below). |
| `body` | `unknown` | Optional. The exact value a catch handler should send back instead of a default `{ code, message }` shape. |
**Return type** — an [`HttpError`](#httperror).
**Factories**
| Factory | Status | `code` | Default `message` |
| -------------------------- | ------ | ------------------------- | --------------------- |
| `Http.BadRequest` | `400` | `'BAD_REQUEST'` | Bad Request |
| `Http.Unauthorized` | `401` | `'UNAUTHORIZED'` | Unauthorized |
| `Http.Forbidden` | `403` | `'FORBIDDEN'` | Forbidden |
| `Http.NotFound` | `404` | `'NOT_FOUND'` | Not Found |
| `Http.MethodNotAllowed` | `405` | `'METHOD_NOT_ALLOWED'` | Method Not Allowed |
| `Http.Conflict` | `409` | `'CONFLICT'` | Conflict |
| `Http.Gone` | `410` | `'GONE'` | Gone |
| `Http.UnprocessableEntity` | `422` | `'UNPROCESSABLE_ENTITY'` | Unprocessable Entity |
| `Http.TooManyRequests` | `429` | `'TOO_MANY_REQUESTS'` | Too Many Requests |
| `Http.InternalServerError` | `500` | `'INTERNAL_SERVER_ERROR'` | Internal Server Error |
| `Http.ServiceUnavailable` | `503` | `'SERVICE_UNAVAILABLE'` | Service Unavailable |
`throw Http.NotFound` — the bare function reference, with no `()` — throws
the function itself, not an `HttpError`. A catch block checking
`instanceof HttpError` won't recognize it, and it reaches the adapter as an
undifferentiated `500` instead. Always call the factory.
**Example**
```ts
import { Http } from '@arcton/core'
throw Http.Conflict('Email already registered', { field: 'email' })
```
## `ValidationError` [#validationerror]
**Purpose** — the error Arcton raises when a `params`, `query` or `body` schema fails (or a body can't be parsed). It reaches [`app.onError()`](./arcton-app.mdx#onerror) like any other error.
**Signature**
```ts no-check
class ValidationError extends HttpError {
constructor(issues: ReadonlyArray)
readonly issues: ReadonlyArray
}
```
**Behavior** — `status` is `400`, `code` is `'VALIDATION_FAILED'`, and `body` is `{ issues }`. `issues` is the exact array the schema library returned, unmodified. With no `onError()` (or one that returns nothing), it answers `400` with `{ "issues": [...] }`. See [Validation Errors](../validation/validation-errors.mdx).
**Example**
```ts
import { Arcton, ValidationError } from '@arcton/core'
const app = Arcton()
app.onError(err => {
if (err instanceof ValidationError) return { issues: err.issues }
})
```
# listen() (/en/docs/api/listen)
`listen()` is the last call in an Arcton application:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
const server = app.listen({ port: 3000 })
console.log(`Listening on ${server.url}`)
```
See [Listen options](../configuration/listen-options.mdx) for the usage-first guide.
## listen [#listen]
**Purpose:** starts the server through the chosen [adapter](./adapters.mdx).
**Signature**
```ts
import type { ArctonListenOptions } from '@arcton/core'
import type { RuntimeServer } from '@arcton/contracts'
declare function listen(options?: ArctonListenOptions): RuntimeServer
```
**Parameters:** an optional `ArctonListenOptions`, documented below.
**Return type:** [`RuntimeServer`](#runtimeserver).
**Behavior:** prints a startup banner — the Arcton figlet logo, the Arcton version, the runtime name and version, the `env`, and the listening URL — then returns a `RuntimeServer`. Routes, `use()`, and `provide()` calls made after `listen()` don't affect requests already flowing through routes registered before it, since each route's pipeline is snapshotted at registration time. Unless `gracefulShutdown` is `false`, it also registers the returned server with a process-wide shutdown coordinator so a `SIGTERM`/`SIGINT` drains it — see [Graceful shutdown](../configuration/listen-options.mdx#graceful-shutdown).
**Errors:** if any [`ws()`](./arcton-app.mdx#ws) route is registered and the chosen adapter's `capabilities.websocket` is `false`, `listen()` throws `Runtime "" does not support WebSocket routes.`. Both shipped adapters — [`bunAdapter` and `nodeAdapter`](./adapters.mdx) — support WebSockets, so this only matters with a custom adapter. It also throws if `shutdownTimeout` is provided but isn't a positive, finite number.
## ArctonListenOptions [#arctonlistenoptions]
**Purpose:** the options object accepted by `listen()`.
**Signature**
```ts
import type { RuntimeAdapter } from '@arcton/contracts'
interface ArctonListenOptions {
port?: number
hostname?: string
adapter?: RuntimeAdapter
env?: string
maxBodySize?: number
gracefulShutdown?: boolean
shutdownTimeout?: number
}
```
**Parameters**
**Behavior:** see [Environment](../configuration/environment.mdx) for what `env` does (and only does), [Runtime types](./runtime-types.mdx) for the `RuntimeAdapter` interface, and [Adapters](./adapters.mdx) for the `bunAdapter`/`nodeAdapter` values.
`gracefulShutdown` and `shutdownTimeout` control the process-wide `SIGTERM`/`SIGINT` handling described in [Graceful shutdown](../configuration/listen-options.mdx#graceful-shutdown). `gracefulShutdown: false` opts a given `listen()` call out entirely — useful when the host application manages process signals itself, since a graceful shutdown ends by calling `process.exit()`, terminating the whole process, not just this server.
## RuntimeServer [#runtimeserver]
**Purpose:** the handle `listen()` returns for the running server.
**Signature**
```ts
interface RuntimeServer {
readonly port: number
readonly url: URL
stop(closeActiveConnections?: boolean): void | Promise
}
```
**Parameters**
**Behavior:** `port` and `url` reflect the address actually bound — useful when `port: 0` picked a free one. `stop()` shuts the server down; it returns `void` on the [Bun adapter](./adapters.mdx) and a `Promise` on the [Node adapter](./adapters.mdx). This is the type used throughout [Testing](../testing/overview.mdx) to start a server on `port: 0`, exercise it with real `fetch` calls, and tear it down afterward.
**Example**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
const res = await fetch(server.url)
console.log(res.status, server.port)
await server.stop()
```
# Logger (/en/docs/api/logger)
## Overview [#overview]
Log one line per request, with no runtime dependency at all:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger())
app.get('/', () => ({ hello: 'world' }))
app.listen()
```
`@arcton/logger` is `app.use()`-only. See
[Logging](../integrations/logger.mdx) for the usage-first guide.
## `logger()` [#logger]
**Purpose** — builds a request-logging middleware.
**Signature**
```ts no-check
function logger(options?: LoggerOptions): ArctonLogger
```
**Parameters**
| Parameter | Type | Description |
| --------- | --------------- | -------------------------------------------- |
| `options` | `LoggerOptions` | Optional. See below for fields and defaults. |
**Return type** — an [`ArctonLogger`](#arctonlogger): a [`Middleware`](./middleware-types.mdx#middleware) with a `.logger` property attached, meant to be passed to `app.use()`.
**Behavior**
* Reads `ctx.request.method` and the request URL's `pathname` (the query string is left out) before calling `next()`.
* With `pretty: false` (the default): once `next()` resolves, logs one JSON line with `method`, `path`, `status` (`ctx.response.status`, defaulting to `200`), and `durationMs` — at `error` for a `5xx` status, `warn` for `4xx`, `info` otherwise.
* With `pretty: true`: logs a `→` line as the request arrives, and a `←` line once it's done (or an `ERR` line if nothing downstream caught a thrown error) — see [Pretty mode](../integrations/logger.mdx#pretty-mode).
* If `next()` rejects — nothing downstream caught the error — logs one line at `error` (JSON) or an `ERR` line (pretty), with the error attached, then rethrows the same error unchanged. No completion line follows.
* `level` gates both formats identically: `'silent'` prints nothing, and a level above what a given line would log at drops just that line.
* Never short-circuits and never touches `ctx.response` itself — a route behaves exactly as it would with no logger registered.
**Errors** — none.
**Example**
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger({ level: 'debug', pretty: true }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.get('/boom', () => {
throw new Error('kaboom')
})
app.listen()
```
## `createLogger()` [#createlogger]
**Purpose** — builds a standalone [`Logger`](#logger), independent of any request. `logger()` above builds one of these internally for its request-logging middleware, but it's just as usable for a background job or at startup.
**Signature**
```ts no-check
function createLogger(options?: LoggerOptions): Logger
```
**Parameters**
| Parameter | Type | Description |
| --------- | --------------- | -------------------------------------------- |
| `options` | `LoggerOptions` | Optional. See below for fields and defaults. |
**Return type** — a [`Logger`](#logger).
**Errors** — none.
**Example**
```ts
import { createLogger } from '@arcton/logger'
const log = createLogger({ level: 'debug' })
log.info('server starting', { pid: process.pid })
const dbLog = log.child({ component: 'database' })
dbLog.info('query executed', { table: 'users' })
```
## `Logger` [#logger-1]
**Purpose** — the interface every logging method (`trace` through `fatal`) and `child()` share, returned by both `createLogger()` and as `.logger` on an [`ArctonLogger`](#arctonlogger).
**Signature**
```ts
interface Logger {
trace(msg: string, data?: Record): void
debug(msg: string, data?: Record): void
info(msg: string, data?: Record): void
warn(msg: string, data?: Record): void
error(msg: string, data?: Record): void
fatal(msg: string, data?: Record): void
child(bindings: Record): Logger
}
```
**Parameters**
**Behavior:** a call below the configured `level` returns immediately — no record is built, no `Date`/serialization cost is paid. `data` on a given call overrides a `bindings` field of the same name for that one record only. A value under `err` (or any key) that's an `Error` serializes to `{ name, message, stack }`, since `JSON.stringify` alone reduces a plain `Error` to `{}`. `child(bindings)` returns a new `Logger` with `bindings` merged into its own — recursively, so a grandchild carries everything its ancestors bound — without mutating the logger it was called on.
**Example**
```ts
import { createLogger } from '@arcton/logger'
const log = createLogger()
log.warn('cache miss', { key: 'user:42' })
const requestLog = log.child({ requestId: 'req_1' })
requestLog.info('handled') // includes requestId: 'req_1'
```
## `LoggerOptions` [#loggeroptions]
**Purpose** — the options object accepted by both `logger()` and `createLogger()`.
**Signature**
```ts
import type { LevelWithSilent } from '@arcton/logger'
interface LoggerOptions {
level?: LevelWithSilent
pretty?: boolean
sink?: (line: string) => void
bindings?: Record
}
```
**Fields**
| Field | Type | Default | Description |
| ---------- | ------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `level` | `LevelWithSilent` | `'info'` | Minimum level to log. Anything below it is dropped before a record is even built. |
| `pretty` | `boolean` | `false` | Formats for a human instead of newline-delimited JSON. |
| `sink` | `(line: string) => void` | writes to `process.stdout` where it exists, `console.log` otherwise | Where each formatted line is written. |
| `bindings` | `Record` | `{}` | Fields merged into every record — what `child()` adds to, not a replacement for it. |
**Behavior:** the default `sink` is resolved once, when `@arcton/logger` loads — `process.stdout.write` on Node/Bun, `console.log` anywhere `process` doesn't exist (a Worker). Pass your own to redirect output — to a file, a test capture, another service — without changing anything else.
## `LogLevel` and `LevelWithSilent` [#loglevel-and-levelwithsilent]
**Purpose** — the level names a `Logger` accepts, and the wider set `LoggerOptions.level` accepts.
**Signature**
```ts
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
type LevelWithSilent = LogLevel | 'silent'
```
**Behavior:** ranked in the order listed, `trace` lowest — a call is written when its own level's rank is at or above the configured minimum's. `'silent'` outranks every real level, so nothing at all passes it.
## `ArctonLogger` [#arctonlogger]
**Purpose** — what `logger()` returns.
**Signature**
```ts no-check
type ArctonLogger = Middleware & {
readonly logger: Logger
}
```
**Behavior** — a plain [`Middleware`](./middleware-types.mdx#middleware) function, so `app.use(logger())` works exactly like [`app.use(cors())`](./cors.mdx). `.logger` is the same [`Logger`](#logger) instance the middleware logs through, for logging anything outside the request/response cycle:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
const log = logger()
app.use(log)
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
log.logger.info(`listening on ${server.url}`)
```
# Middleware Types (/en/docs/api/middleware-types)
A [`Middleware`](#middleware) is a plain function — no class, no decorator, nothing beyond passing it to [`app.use()`](./arcton-app.mdx#use) or a route:
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const logger: Middleware = async (ctx, next) => {
console.log(ctx.request.method, ctx.request.url)
await next()
}
const app = Arcton()
app.use(logger)
app.get('/', () => 'ok')
app.listen()
```
## Middleware [#middleware]
**Purpose:** the shape of every global, scoped, and route middleware function.
**Signature**
```ts
import type { Body, Context, NextFunction, QueryParams, RouteParams } from '@arcton/contracts'
type Middleware = (
ctx: Context
,
next: NextFunction
) => Promise
| Body | void
```
**Behavior:** the generic parameter order — `P, Q, TBody, TProvided` — is load-bearing: it matches [`Context`](./context.mdx)'s own order. Code before `await next()` runs on the way in; code after runs on the way out. Returning a value without calling `next()` short-circuits the pipeline — nothing downstream runs. See [Execution order](../middleware/execution-order.mdx).
## NextFunction [#nextfunction]
**Purpose:** advances the pipeline to the next step.
**Signature**
```ts
type NextFunction = () => Promise
```
**Behavior:** calls the next middleware (or the handler, if there is none left) and resolves once everything downstream has finished.
## RouteHandler [#routehandler]
**Purpose:** the shape of a route's final handler.
**Signature**
```ts
import type { Body, Context, QueryParams, RouteParams } from '@arcton/contracts'
type RouteHandler = (
ctx: Context
) => (Body | void) | Promise
```
**Behavior:** the same shape as [`Middleware`](#middleware), minus `next` — a handler always runs last, so it has nothing to call. This is the type of the trailing argument to `get`/`post`/etc. and of `RouteOptions.handler`.
## ErrorHandler [#errorhandler]
**Purpose:** the shape of the handler passed to [`app.onError()`](./arcton-app.mdx#onerror).
**Signature**
```ts
import type { Body, Context, QueryParams, RouteParams } from '@arcton/contracts'
type ErrorHandler = (
err: unknown,
ctx: Context
) => (Body | void) | Promise
```
**Behavior:** the same shape as [`RouteHandler`](#routehandler), with the caught error prepended as the first argument. `err` is `unknown`, not `Error` — a thrown value in JavaScript isn't guaranteed to be one. See [Global error handler](../errors/global-error-handler.mdx).
## MatchResult [#matchresult]
**Purpose:** the result of matching a method and path against the route tree.
**Signature**
```ts
import type { HttpMethod, RouteHandler, RouteParams } from '@arcton/contracts'
type MatchResult =
| { matched: true; handler: RouteHandler; params: RouteParams }
| { notFound: true }
| { methodNotAllowed: true; allowed: HttpMethod[] }
```
**Behavior:** `Router.match()`'s return value, described next. Application code doesn't construct or read this directly — it's exposed for anyone implementing a custom [`RuntimeAdapter`](./runtime-types.mdx).
## Router [#router]
**Purpose:** the internal interface `ArctonApp` uses to resolve a request to a handler.
**Signature**
```ts
import type { HttpMethod, MatchResult } from '@arcton/contracts'
interface Router {
match(method: HttpMethod, url: string): MatchResult
}
```
**Behavior:** see [Precedence](../routing/precedence.mdx) for the matching rules — static beats dynamic beats wildcard, with backtracking.
## ReservedKeys [#reservedkeys]
**Purpose:** the keys [`provide()`](./arcton-app.mdx#provide) refuses to add.
**Signature**
```ts
import type { BaseContext } from '@arcton/contracts'
type ReservedKeys =
| keyof BaseContext
| 'body'
| 'contentType'
| keyof TProvided
```
**Behavior:** covers the base `Context` fields (`request`/`params`/`query`/`response`), `'body'`, `'contentType'`, and any key already provided earlier in the chain. Re-providing one of these is a compile error, not a runtime one.
## ProvideFn [#providefn]
**Purpose:** the function shape passed to [`app.provide()`](./arcton-app.mdx#provide).
**Signature**
```ts
import type { Context, QueryParams, RouteParams } from '@arcton/contracts'
type ProvideFn> = (
ctx: Context
) => R | Promise
```
**Behavior:** runs before route-level validation, so it only ever sees the raw `params`/`query` defaults — never a route's schema output. Its return value, `R`, is merged flat onto `ctx`. See [Providers](../providers/overview.mdx).
# OpenAPI (/en/docs/api/openapi)
## Overview [#overview]
Serve an OpenAPI 3.1 document and a Scalar UI reading it, generated from a
route's own `params`/`query`/`body`/`response`/`detail`:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.use(openapi({ info: { title: 'API', version: '1.0.0' } }))
app.listen()
```
See [OpenAPI & Scalar](../integrations/openapi.mdx) for the usage-first
guide.
## `openapi()` [#openapi]
**Purpose** — builds the middleware that serves the document and the Scalar
page. Register it with `app.use()`.
**Signature**
```ts no-check
import type { RouteAwareMiddleware } from '@arcton/contracts'
function openapi(options: OpenAPIOptions): RouteAwareMiddleware
```
**Parameters**
| Parameter | Type | Description |
| --------- | ---------------- | --------------------------------------------------------- |
| `options` | `OpenAPIOptions` | Required — at minimum, `info`. See below for every field. |
**Return type** — a [`RouteAwareMiddleware`](#routeawaremiddleware).
**Behavior** — answers `GET` requests to the document (`document.path`,
default `/openapi.json`) and, unless `docs: false`, to a Scalar page
(`docs.path`, default `/docs`) that loads the document by URL rather than
embedding a second copy of it. Every other request goes on to `next()`. The
document is built once, on the first request for it — after every module has
been mounted — and never per request. It runs in registration order like any
middleware, so one registered after an auth middleware is protected by it.
**Errors** — no registration error: a route at one of the same paths is
shadowed when `openapi()` was registered before it, and answers normally
when it was registered after. Using `openapi()` anywhere but `app.use()` (a route's own middleware,
for example) throws `openapi() must be registered with app.use()` on the
first request for the document.
**Example**
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
import * as z from 'zod'
const app = Arcton()
app.get('/users/:id', {
params: z.object({ id: z.uuid() }),
response: z.object({ id: z.string() }),
detail: { operationId: 'getUser', tags: ['Users'] },
handler: ctx => ({ id: ctx.params.id })
})
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
docs: { path: '/reference' }
})
)
app.listen({ port: 3000 })
```
## `OpenAPIOptions` [#openapioptions]
**Purpose** — the options object accepted by `openapi()`.
**Signature**
```ts no-check
interface OpenAPIOptions extends DocumentOptions {
document?: { path?: string }
docs?: (ScalarOptions & { path?: string }) | false
}
```
**Fields**
| Field | Type | Default | Description |
| --------------- | ------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `info` | `OpenAPIInfo` | — | Required — see [`DocumentOptions`](#documentoptions). |
| `servers` | `object[]` | — | See [`DocumentOptions`](#documentoptions). |
| `tags` | `object[]` | — | See [`DocumentOptions`](#documentoptions). |
| `security` | `object[]` | — | See [`DocumentOptions`](#documentoptions). |
| `document.path` | `string` | `'/openapi.json'` | Where the document itself is served. |
| `docs` | `ScalarOptions \| false` | `{}` | Scalar's own options — see [`ScalarOptions`](#scalaroptions) — plus `path` (default `'/docs'`). `false` serves the document alone, with no UI. |
**Behavior** — `document` and `docs` are kept separate from `info`/
`servers`/`tags`/`security` on purpose: one side describes the API, the
other describes the UI reading it. See [Configuring the
paths](../integrations/openapi.mdx#configuring-the-paths) and [Configuring
Scalar](../integrations/openapi.mdx#configuring-scalar).
## `OpenAPIInfo` [#openapiinfo]
**Purpose** — the document's `info` object — the one required field of
`OpenAPIOptions`.
**Signature**
```ts
interface OpenAPIInfo {
title: string
version: string
description?: string
[key: string]: unknown
}
```
**Fields**
| Field | Type | Description |
| ------------- | -------- | -------------------------------------------------------------------------------------------- |
| `title` | `string` | The API's name. |
| `version` | `string` | The API's own version — unrelated to the OpenAPI spec version (`3.1.0`, always set for you). |
| `description` | `string` | Optional. |
**Behavior** — any other OpenAPI `info` field (`termsOfService`, `contact`,
`license`, ...) is accepted through the index signature and passed straight
through to the document, unvalidated.
## `DocumentOptions` [#documentoptions]
**Purpose** — the document-level fields `OpenAPIOptions` extends; also what
[`buildDocument()`](#builddocument) itself takes.
**Signature**
```ts no-check
interface DocumentOptions {
info: OpenAPIInfo
servers?: Record[]
tags?: Record[]
security?: Record[]
}
```
**Fields**
| Field | Type | Description |
| ---------- | ------------- | -------------------------------------------------------------- |
| `info` | `OpenAPIInfo` | See [`OpenAPIInfo`](#openapiinfo). |
| `servers` | `object[]` | OpenAPI Server Objects, passed through as given. |
| `tags` | `object[]` | OpenAPI Tag Objects, passed through as given. |
| `security` | `object[]` | OpenAPI Security Requirement Objects, passed through as given. |
**Behavior** — `servers`/`tags`/`security` are copied onto the document
verbatim when present, and omitted entirely otherwise — none of the three
has a default.
## `ScalarOptions` [#scalaroptions]
**Purpose** — Scalar's own configuration, under `OpenAPIOptions.docs`.
**Signature**
```ts
interface ScalarOptions {
pageTitle?: string
cdn?: string
configuration?: Record
}
```
**Fields**
| Field | Type | Default | Description |
| --------------- | -------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `pageTitle` | `string` | `'Scalar API Reference'` | The `` of the `/docs` page. |
| `cdn` | `string` | jsDelivr | Where Scalar's JS bundle is loaded from — set to point at a self-hosted build. |
| `configuration` | `object` | `{}` | Scalar's own configuration object (theme, sidebar, auth, ...) — see [Scalar's configuration docs](https://guides.scalar.com/scalar/scalar-api-references/configuration). |
**Behavior** — `configuration.url` is always set for you, from
`OpenAPIOptions.document.path` — the page reads the document by URL, so it
never embeds a second copy of it. Any `url` passed in `configuration` is
overridden.
## `buildDocument()` [#builddocument]
**Purpose** — the lower-level function `openapi()` itself calls: turns a set
of route records straight into an OpenAPI document object, with no HTTP
integration. Useful for writing the document to a file at build time, or for
testing what a set of routes produces without starting a server.
**Signature**
```ts no-check
import type { RouteRecord } from '@arcton/contracts'
function buildDocument(
records: readonly RouteRecord[],
options: DocumentOptions
): Record
```
**Parameters**
| Parameter | Type | Description |
| --------- | ------------------------ | --------------------------------------------------------------------- |
| `records` | `readonly RouteRecord[]` | Typically the result of [`routesOf(app)`](./arcton-app.mdx#routesof). |
| `options` | `DocumentOptions` | See [`DocumentOptions`](#documentoptions) above. |
**Return type** — a plain, JSON-serializable OpenAPI 3.1 document.
**Example**
```ts
import { Arcton, routesOf } from '@arcton/core'
import { buildDocument } from '@arcton/openapi'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
const document = buildDocument(routesOf(app), {
info: { title: 'Users API', version: '1.0.0' }
})
await Bun.write('openapi.json', JSON.stringify(document, null, 2))
```
## `RouteRecord` [#routerecord]
**Purpose** — what a route declared, kept alongside the route tree so it
survives after registration — the tree itself stores only composed
handlers. Read through [`routesOf(app)`](./arcton-app.mdx#routesof); this is
also what a [`RouteAwareMiddleware`](#routeawaremiddleware) reads.
**Signature**
```ts no-check
import type { StandardSchemaV1 } from '@arcton/contracts'
interface RouteRecord {
method: HttpMethod
path: string
params?: StandardSchemaV1
query?: StandardSchemaV1
body?: StandardSchemaV1
bodyContent?: Record
bodyOptional?: boolean
response?: Record
detail?: RouteDetail
}
```
**Fields**
| Field | Type | Description |
| ----------------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `method` | `HttpMethod` | One concrete method — `app.all()` produces one record per method it registers, never an "any method" record. |
| `path` | `string` | The route's final path, with every mounting prefix already applied. |
| `params`/`query`/`body` | `StandardSchemaV1` | The original schema instances, not a converted form — see [`StandardSchemaV1`](./validation-types.mdx#standardschemav1). |
| `bodyContent` | `Record` | Set instead of `body` when the route lists the media types it accepts (keys lowercased, no parameters). Each one becomes an entry of `requestBody.content`. |
| `bodyOptional` | `boolean` | `true` when the route accepts a request with no body — its `requestBody` is documented without `required`. |
| `response` | `Record` | Normalized from `RouteOptions.response` — always keyed by status, even when a bare schema was given. |
| `detail` | `RouteDetail` | See [`RouteDetail`](./arcton-app.mdx#routedetail). |
**Behavior** — a `ws()` route produces no record, having no contract to
describe. See [`routesOf()`](./arcton-app.mdx#routesof) for how records
compose across mounted modules.
## `RouteAwareMiddleware` [#routeawaremiddleware]
**Purpose** — a `Middleware` that documents or inspects the app it is
registered on. `openapi()` returns one.
**Signature**
```ts no-check
interface RouteAwareMiddleware extends Middleware {
bindRoutes(routes: () => readonly RouteRecord[]): void
}
```
**Behavior** — when it is passed to `use()` (scoped or not), the app calls
`bindRoutes` once with a reader of its own `RouteRecord[]`. The reader is
live, so calling it at request time sees every module mounted by then;
`@arcton/core` never needs to know which package is on the other end.
# Runtime Types (/en/docs/api/runtime-types)
## Overview [#overview]
These types define what a `RuntimeAdapter` is and what it hands back — they're the contract `bunAdapter` and `nodeAdapter` (see [Adapters](./adapters.mdx)) implement, and the shapes you'd need if you wrote your own. Most applications never touch these directly; they matter when you're passing `adapter` to `app.listen()` or authoring a new one.
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello from Node')
app.listen({ adapter: nodeAdapter })
```
## `RuntimeAdapter` [#runtimeadapter]
**Purpose** — the interface a runtime integration implements so `@arcton/core` can serve requests without importing Bun or Node APIs itself.
**Signature**
```ts no-check
interface RuntimeAdapter {
readonly name: string
readonly version: string
readonly capabilities: RuntimeCapabilities
serve(options: RuntimeServeOptions): RuntimeServer
}
```
**Behavior** — `name` and `version` identify the runtime (used in the startup banner printed by `listen()`, see [listen()](./listen.mdx)). `capabilities.websocket` is checked once, inside `listen()`, against whatever `ws()` routes exist at that point (including ones added by mounting a module) — not at `ws()`-registration time.
**Example** — see [Adapters](./adapters.mdx) for the two concrete, shipped values.
## `RuntimeCapabilities` [#runtimecapabilities]
**Purpose** — declares what an adapter supports.
**Signature**
```ts
interface RuntimeCapabilities {
readonly websocket: boolean
}
```
**Behavior** — both shipped adapters set `websocket: true`. If `websocket` is `false` on the adapter passed to `listen()` and the app has registered `ws()` routes, `listen()` throws.
## `RuntimeHandler` [#runtimehandler]
**Purpose** — the function shape of the HTTP request handler an adapter's `serve()` is given.
**Signature**
```ts no-check
type RuntimeHandler = (
request: Request,
context: RuntimeRequestContext
) => Response | undefined | Promise
```
**Parameters**
| Parameter | Type | Description |
| --------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `request` | `Request` | The incoming request. A request that carries no body must have `request.body === null`, not an empty stream — that is how a route with an [optional body](../validation/body.mdx#optional-bodies) tells the two apart. |
| `context` | `RuntimeRequestContext` | Runtime-provided helpers, currently just the low-level WebSocket upgrade primitive. |
**Return type** — a `Response`, or `undefined` when the handler has already completed the request another way (for example, a successful WebSocket upgrade).
## `RuntimeServeOptions` [#runtimeserveoptions]
**Purpose** — what's passed into `RuntimeAdapter.serve()`.
**Signature**
```ts no-check
interface RuntimeServeOptions {
fetch: RuntimeHandler
port: number
hostname?: string
websocket?: RuntimeWebSocketRoute[]
}
```
**Behavior** — `websocket` lists every `ws()` route registered on the app (including ones grafted in by mounting a module); the adapter is expected to auto-upgrade requests that match one of these paths, ahead of calling `fetch` at all.
## `RuntimeRequestContext` [#runtimerequestcontext]
**Purpose** — the low-level WebSocket upgrade primitive handed to a `RuntimeHandler`, for upgrades that can't be expressed as a static `websocket` route entry (for example, one gated on auth).
**Signature**
```ts no-check
interface RuntimeRequestContext {
upgrade(request: Request, options?: RuntimeUpgradeOptions): boolean
}
```
**Parameters**
| Parameter | Type | Description |
| --------- | ----------------------- | --------------------------------- |
| `request` | `Request` | The request to upgrade. |
| `options` | `RuntimeUpgradeOptions` | Optional upgrade payload/headers. |
**Return type** — `boolean`: `true` if the upgrade succeeded, `false` otherwise.
**Behavior** — only usable when `RuntimeAdapter.capabilities.websocket` is `true`. On success, the handler must not also return a `Response`; on failure (`false`), the handler should return an error `Response` itself.
**Example** — a fragment showing the primitive, not a full adapter:
```ts
import type { RuntimeHandler } from '@arcton/contracts'
const fetchFallback: RuntimeHandler = (request, context) => {
if (new URL(request.url).pathname === '/socket') {
return context.upgrade(request)
? undefined
: new Response('Upgrade failed', { status: 400 })
}
return new Response('not found', { status: 404 })
}
```
## `RuntimeUpgradeOptions` [#runtimeupgradeoptions]
**Purpose** — optional data passed alongside a `RuntimeRequestContext.upgrade()` call.
**Signature**
```ts
interface RuntimeUpgradeOptions {
data?: unknown
headers?: Record
}
```
**Behavior** — `data` becomes the WebSocket's `RuntimeWebSocket.data` once the connection is open.
## `RuntimeWebSocket` [#runtimewebsocket]
**Purpose** — the WebSocket handle passed to a `RuntimeWebSocketHandler`'s callbacks.
**Signature**
```ts
interface RuntimeWebSocket {
readonly data: unknown
send(message: string | ArrayBuffer | ArrayBufferView): void
close(code?: number, reason?: string): void
}
```
**Behavior** — `data` carries whatever payload the upgrade produced; it is `undefined` unless something explicitly attached one (see `RuntimeUpgradeOptions`).
## `RuntimeWebSocketHandler` [#runtimewebsockethandler]
**Purpose** — the callbacks for a registered `ws()` route.
**Signature**
```ts no-check
interface RuntimeWebSocketHandler {
message(ws: RuntimeWebSocket, message: string | ArrayBuffer): void | Promise
open?(ws: RuntimeWebSocket): void | Promise
close?(ws: RuntimeWebSocket, code: number, reason: string): void | Promise
drain?(ws: RuntimeWebSocket): void | Promise
}
```
**Behavior** — only `message` is required. See [WebSockets](../routing/websockets.mdx) for `app.ws()` itself and worked examples.
**Example** — a fragment showing the shape:
```ts
import type { RuntimeWebSocketHandler } from '@arcton/contracts'
const echoHandler: RuntimeWebSocketHandler = {
message(ws, message) {
if (message === 'bye') {
ws.close(1000, 'client said bye')
return
}
ws.send(message)
}
}
```
## `RuntimeWebSocketRoute` [#runtimewebsocketroute]
**Purpose** — one entry in `RuntimeServeOptions.websocket`.
**Signature**
```ts no-check
interface RuntimeWebSocketRoute {
path: string
handler: RuntimeWebSocketHandler
}
```
## `RuntimeServer` [#runtimeserver]
**Purpose** — what `RuntimeAdapter.serve()` returns, and what `app.listen()` returns to the caller.
**Signature**
```ts
interface RuntimeServer {
readonly port: number
readonly url: URL
stop(closeActiveConnections?: boolean): void | Promise
}
```
**Behavior** — `stop()` returns `void` on the Bun adapter and a `Promise` on the Node adapter (see [Adapters](./adapters.mdx)); `await`-ing it works either way. Full usage — including `port: 0` to pick a free port — is covered in [listen()](./listen.mdx).
# Validation Types (/en/docs/api/validation-types)
## Overview [#overview]
Two type-level contracts make request validation and custom body parsing work without Arcton depending on a specific schema or parsing library: `StandardSchemaV1`, the interface `params`/`query`/`body` schemas must implement, and `BodyParser`, the function shape a custom parser registered with `app.parser()` must implement. See [Application](./arcton-app.mdx) for where both are consumed.
## `StandardSchemaV1` [#standardschemav1]
**Purpose** — a vendor-neutral schema interface ([standardschema.dev](https://standardschema.dev/)) implemented by Zod 3.24+, Valibot, ArkType, and others. Any schema that implements it can be passed as `params`, `query`, or `body` on the route-options call shape.
**Signature**
```ts
interface StandardSchemaV1 {
readonly '~standard': StandardSchemaV1.Props
}
namespace StandardSchemaV1 {
export interface Props {
readonly version: 1
readonly vendor: string
readonly validate: (
value: unknown
) => Result | Promise>
readonly types?: Types | undefined
}
export interface Types {
readonly input: Input
readonly output: Output
}
export type Result = SuccessResult | FailureResult
export interface SuccessResult {
readonly value: Output
readonly issues?: undefined
}
export interface FailureResult {
readonly issues: ReadonlyArray
}
export interface Issue {
readonly message: string
readonly path?: ReadonlyArray | undefined
}
export interface PathSegment {
readonly key: PropertyKey
}
export type InferOutput = NonNullable<
Schema['~standard']['types']
>['output']
}
```
**Behavior** — `validate()` returns a `SuccessResult` (`{ value }`) or a `FailureResult` (`{ issues }`), synchronously or via a `Promise`. `types` is a phantom field: it's never populated at runtime, only read through `StandardSchemaV1.InferOutput` so TypeScript can infer the validated output type at zero runtime cost. When a route declares a schema, its `InferOutput` — not the pre-validation input — is what `ctx.params`, `ctx.query`, or `ctx.body` are typed and populated as; see [Context](./context.mdx).
**Errors** — none of its own. A schema's `validate()` returning `{ issues }` short-circuits the request with a `400` response; the issues array is passed straight through to the client.
**Example**
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
body: v.object({
item: v.pipe(v.string(), v.minLength(1)),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
handler: ctx => ({
userId: ctx.params.id,
order: ctx.body
})
})
app.listen()
```
This fragment shows the interface directly, without a schema library, by implementing it by hand:
```ts
import type { StandardSchemaV1 } from '@arcton/contracts'
function positiveNumber(): StandardSchemaV1 {
return {
'~standard': {
version: 1,
vendor: 'example',
validate(value) {
const n = Number(value)
return n > 0
? { value: n }
: { issues: [{ message: 'must be a positive number' }] }
}
}
}
}
```
## `StandardJSONSchemaV1` [#standardjsonschemav1]
**Purpose** — a sibling to `StandardSchemaV1` ([Standard JSON Schema](https://standardschema.dev/json-schema)), implemented by a schema that can also describe itself as JSON Schema. Nothing in `@arcton/core` reads this — it exists so a package built on top of Arcton, like [`@arcton/openapi`](./openapi.mdx), can generate documentation from the very schemas a route already validates with.
**Signature**
```ts
interface StandardJSONSchemaV1 {
readonly '~standard': StandardJSONSchemaV1.Props
}
namespace StandardJSONSchemaV1 {
export interface Props {
readonly jsonSchema: Converter
}
export interface Converter {
readonly input: (options: Options) => Record
readonly output: (options: Options) => Record
}
export type Target =
| 'draft-2020-12'
| 'draft-07'
| 'openapi-3.0'
| ({} & string)
export interface Options {
readonly target: Target
readonly libraryOptions?: Record | undefined
}
}
```
**Behavior** — shares the same `'~standard'` key as `StandardSchemaV1`, so a schema that supports it is detected by feature (`'jsonSchema' in schema['~standard']`), not by which library produced it. `input` and `output` are separate conversions because they can differ — a schema with a transform accepts one shape and produces another. Either may throw when a schema has no JSON Schema representation at all (a raw `Date`, for instance); a caller that wants documentation instead of an error should catch that itself. Zod 4.6+ and ArkType 2.2+ implement this out of the box; Valibot doesn't yet — wrap a schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` to opt in. See [OpenAPI & Scalar](../integrations/openapi.mdx#schema-requirements).
**Example**
This fragment shows the interface directly, without a schema library, by implementing it by hand:
```ts
import type { StandardJSONSchemaV1 } from '@arcton/contracts'
function jsonString(): StandardJSONSchemaV1 {
return {
'~standard': {
jsonSchema: {
input: () => ({ type: 'string' }),
output: () => ({ type: 'string' })
}
}
}
}
```
## `BodyParser` [#bodyparser]
**Purpose** — the function shape registered with `app.parser(mediaType, parser)` to parse a request body for a media type, overriding or extending the built-ins. See [Application](./arcton-app.mdx) for `parser()` itself.
**Signature**
```ts
type BodyParser = (request: Request) => unknown | Promise
```
**Parameters**
| Parameter | Type | Description |
| --------- | --------- | --------------------------------------------------------------------------------------------------------- |
| `request` | `Request` | The raw incoming request — not `ctx`, since parsing happens before a context's params/query are relevant. |
**Return type** — `unknown | Promise`: whatever value should become the schema's validation input for that route's `body` option.
**Behavior** — returning `undefined` means "I don't handle this," so the runtime keeps looking (and ultimately responds `415` if nothing else does). Any other value counts as handled, including `false`, `0`, and `''`. A parser is only ever consulted for a route that declares a `body` schema and lists the media type in `content`.
**Errors** — a parser that throws propagates like any other user code (see [Uncaught errors](../errors/uncaught-errors.mdx)); it is not caught and converted into a `400`.
**Example**
```ts
import { Arcton } from '@arcton/core'
import type { BodyParser } from '@arcton/contracts'
import * as v from 'valibot'
const csvParser: BodyParser = async request => {
const text = await request.text()
const [header = '', ...rows] = text.trim().split('\n')
const keys = header.split(',')
return rows.map(row =>
Object.fromEntries(keys.map((key, i) => [key, row.split(',')[i]]))
)
}
const app = Arcton()
app.parser('text/csv', csvParser)
app.post('/import', {
body: {
content: { 'text/csv': v.array(v.record(v.string(), v.string())) }
},
handler: ctx => ({ imported: ctx.body.length, rows: ctx.body })
})
app.listen()
```
See [Body parsers](../validation/body-parsers.mdx) for the built-in parser table and how a route's `body` schema selects one.
# Global Error Handler (/en/docs/errors/global-error-handler)
[Uncaught errors](./uncaught-errors.mdx) reach the runtime adapter as a bare
`500` unless something catches them first. `app.onError()` registers a single
handler that catches any of those — from a provider, a middleware, a body
parser, or the route handler itself — before it gets that far:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/risky', () => {
throw new Error('boom')
})
app.onError((err, ctx) => {
console.error(err)
return { error: 'Something went wrong' }
})
app.listen()
```
A request to `/risky` now answers with the handler's own response instead of
the adapter's generic `500` text. `onError()` is opt-in — an app that never
calls it keeps behaving exactly like [Uncaught errors](./uncaught-errors.mdx)
describes.
## The status defaults to 500 [#the-status-defaults-to-500]
If the handler doesn't set `ctx.response.status` itself, the response
defaults to `500`. Set it explicitly to answer with something else — for
example, narrowing on `HttpError` to reuse the status it already carries:
```ts
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.onError((err, ctx) => {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
return { code: 'INTERNAL_SERVER_ERROR', message: 'Internal Server Error' }
})
app.listen()
```
A status set earlier in the request — by a middleware that ran before the
throw, say — is left alone if the handler never touches `ctx.response.status`
itself; the `500` default only fills in when nothing set a status at all.
Like any handler, `onError()` can return a plain value (mapped through the
usual [Response](../fundamentals/response.mdx) rules) or a `Response` object
directly, which is sent through unchanged.
## Validation errors go through it too [#validation-errors-go-through-it-too]
A failed `params`, `query` or `body` schema — or a body Arcton can't parse at
all — reaches `onError()` as a `ValidationError`: an `HttpError` subclass whose
`issues` are exactly what the schema library returned. An unsupported body
`Content-Type` arrives as an `HttpError` with status `415`.
```ts
import { Arcton, ValidationError } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({ email: v.pipe(v.string(), v.email()) }),
handler: ctx => ({ created: ctx.body })
})
app.onError((err, ctx) => {
if (err instanceof ValidationError) {
return { error: 'Invalid request', issues: err.issues }
}
return { error: 'Something went wrong' }
})
app.listen()
```
The response above is a `400` even though the handler never set a status: for
these two request errors the status defaults to their own (`400`, `415`)
instead of `500`.
Validation errors are answered right where they happen, so middleware wrapping
the route — CORS, request logging — still sees a normal response after
`await next()`. Any other thrown error unwinds through that middleware first.
## Returning nothing declines the error [#returning-nothing-declines-the-error]
`onError()` handles an error by returning a value or a `Response`. If it
returns nothing, Arcton's default applies instead: a validation error answers
`400` with the [issues body](../validation/validation-errors.mdx), an
unsupported `Content-Type` answers an empty `415`, and any other error
propagates to the adapter exactly as it would with no handler registered. That
makes `onError()` a fine place to log everything and only take over the
responses you care about.
## Runs for the 404/405 fallback too [#runs-for-the-404405-fallback-too]
Global [middleware](../middleware/global.mdx) runs even when nothing matches
the request, so `onError()` covers a throw there as well:
```ts
import { Arcton } from '@arcton/core'
declare function logRequest(request: Request): void
const app = Arcton()
app.use(async (ctx, next) => {
logRequest(ctx.request) // throws if the logger is down
await next()
})
app.onError((err, ctx) => ({ error: 'Something went wrong' }))
app.listen()
```
## It's a single, top-level handler [#its-a-single-top-level-handler]
Only one `onError()` handler exists per app — registering a second one
replaces the first — and only the instance whose own `listen()` ends up
serving the request is ever consulted. If you build part of your app as a
separate module and mount it with `app.use(module)`, an `onError()` call on
that module has no effect; modules compose routes, middleware, and
providers into the mounting app, not an independent error boundary.
For a boundary scoped to one section of the app, wrap `next()` in a
try/catch inside a [scoped middleware](../middleware/scoped.mdx) instead —
see [Catch a thrown error inside middleware](./responding-with-errors.mdx#catch-a-thrown-error-inside-middleware).
The two compose fine together: a scoped try/catch handles what it recognizes
and rethrows anything else, which then reaches `onError()` as the final
catch-all.
If the `onError()` handler itself throws, that error isn't passed back
in — it propagates the same way an uncaught error would with no handler
registered at all.
# Errors (/en/docs/errors/overview)
## Every response goes through the same mapping [#every-response-goes-through-the-same-mapping]
Arcton doesn't have a separate channel for error responses. A handler that
hits a problem responds exactly the way a handler that succeeds does: by
returning a `Response`, by returning a plain value that gets mapped to one, or
by setting `ctx.response` before the body finalizes.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => {
if (ctx.params.id === '0') {
return new Response('Not found', { status: 404 })
}
return { id: ctx.params.id }
})
app.listen()
```
That single idea covers three situations you'll run into:
* **Something the caller did wrong** — a missing header, a bad id, a request
body that fails validation. You (or Arcton's own validation) respond with a
4xx `Response`, optionally by throwing one of `@arcton/core`'s ready-made
`HttpError`s (see [HTTP errors](../api/http-errors.mdx)). See
[Responding with errors](./responding-with-errors.mdx).
* **Something you didn't handle** — a thrown exception in a handler, a
provider, or a custom body parser. See
[Uncaught errors](./uncaught-errors.mdx).
* **Something wrong with how a route or a piece of middleware was
registered** — a duplicate route, a bad parameter name, a non-static scope.
These fail immediately, at startup, before any request arrives. See
[Registration errors](./registration-errors.mdx).
# Registration Errors (/en/docs/errors/registration-errors)
## Checked once, at registration time [#checked-once-at-registration-time]
Building a route tree happens once, when your module loads — calling
`.get()`/`.post()`/etc., `.use()`, `.ws()`, or `Arcton({ prefix })` itself.
Arcton validates each of these calls immediately and throws synchronously if
something's wrong, so a mistake fails fast at startup instead of turning into
a confusing match at request time.
## Duplicate route [#duplicate-route]
Registering the same method and path twice throws:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/x', () => 'first')
app.get('/x', () => 'second')
app.listen()
```
```
Duplicate route: GET /x is already registered
```
This also fires when mounting a module produces a duplicate — see
[Modules](../routing/modules.mdx).
## Conflicting parameter name [#conflicting-parameter-name]
Two different parameter names can't occupy the same position in the route
tree:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ctx.params.id)
app.get('/users/:userId', ctx => ctx.params.userId)
app.listen()
```
```
Conflicting parameter name: "userId" conflicts with "id" at same position
```
A dynamic and a wildcard segment at the same position don't conflict with
each other — only two dynamic segments, or two wildcard segments, with
different names do. See [Precedence](../routing/precedence.mdx).
## Invalid parameter name [#invalid-parameter-name]
A `:param` or `*wildcard` name must start with a letter and contain only
letters, digits or `_`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:1id', ctx => ctx.params)
app.listen()
```
```
Invalid dynamic parameter name ":1id" in route "/users/:1id": must start with a letter and contain only letters, digits or "_"
```
The same check, with "wildcard" in place of "dynamic", applies to `*name`
segments.
## Duplicate parameter name in one route [#duplicate-parameter-name-in-one-route]
The same param name can't appear twice in a single route:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/pair/:a/:a', ctx => ctx.params.a)
app.listen()
```
```
Duplicate parameter name "a" in route "/pair/:a/:a"
```
## Wildcard segment position [#wildcard-segment-position]
A `*wildcard` segment must be the last segment in the route:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/files/*path/edit', ctx => ctx.params.path)
app.listen()
```
```
Wildcard segment must be the last segment in route "/files/*path/edit"
```
## Path format [#path-format]
Every route path must start with `/` and must not contain an empty segment:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('users', () => 'nope')
app.listen()
```
```
Route path must start with "/", got "users"
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users//profile', () => 'nope')
app.listen()
```
```
Route path must not contain empty segments ("//"): "/users//profile"
```
## Static prefixes and scopes [#static-prefixes-and-scopes]
`ArctonConfig.prefix` and the `scope` in `use(scope, middleware)` must both
be static paths — no `:param` or `*wildcard` segments:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api/:version' })
app.listen()
```
```
Prefix "/api/:version" must be a static path — dynamic/wildcard segments aren't supported (e.g. app.use('/api', mw), not app.use('/api/:id', mw))
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/users/:id', async (ctx, next) => {
await next()
})
app.listen()
```
```
Scope "/users/:id" must be a static path — dynamic/wildcard segments aren't supported (e.g. app.use('/api', mw), not app.use('/api/:id', mw))
```
## use() with the wrong argument [#use-with-the-wrong-argument]
`use()` accepts a middleware function, a `(scope, middleware)` pair, or an
Arcton app to mount as a module — anything else throws:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use({} as never)
app.listen()
```
```
use() expects a middleware function, a (scope, middleware) pair, or an Arcton app to mount
```
# Responding with Errors (/en/docs/errors/responding-with-errors)
## Return a Response and skip the mapping entirely [#return-a-response-and-skip-the-mapping-entirely]
Returning a `Response` object from a handler is passed straight through — no
header merge, no status validation. It's the most direct way to answer a
request that can't succeed:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/profile', ctx => {
const token = ctx.request.headers.get('authorization')
if (token !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
return { user: 'Alice' }
})
app.listen()
```
## Set ctx.response.status and return a plain value [#set-ctxresponsestatus-and-return-a-plain-value]
If you'd rather keep returning a plain object and let Arcton serialize it to
JSON, set the status on `ctx.response` before the handler returns:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/orders', ctx => {
ctx.response.status = 201
return { created: true }
})
app.listen()
```
`ctx.response.status` can only be set before the response body finalizes —
inside the handler, or before `await next()` in a global or route middleware.
Once the body finalizes (the handler returns, a step short-circuits, or a
layer replaces the body after `next()`), `ctx.response` has become a real
`Response`, whose `status` has no setter — assigning to it throws
`TypeError: Attempted to assign to readonly property.`. Header mutation is
different: `ctx.response.headers.set(...)` / `.append(...)` keeps working
after `await next()` and still reaches the client.
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const timing: Middleware = async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
}
const app = Arcton()
app.use(timing)
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
## Catch a thrown error inside middleware [#catch-a-thrown-error-inside-middleware]
A middleware is a plain async function, so wrapping `await next()` in a
try/catch turns whatever the rest of the chain throws into a normal response:
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const catchErrors: Middleware = async (ctx, next) => {
try {
await next()
} catch (error) {
ctx.response.status = 500
return { error: error instanceof Error ? error.message : 'Unknown error' }
}
}
const app = Arcton()
app.use(catchErrors)
app.get('/risky', () => {
throw new Error('boom')
})
app.listen()
```
Because the throw happens before the handler's own return value finalizes the
response, `ctx.response.status` is still writable when the `catch` block
runs.
For a single catch-all instead of a try/catch in every middleware, see
[Global error handler](./global-error-handler.mdx).
## Throw a ready-made HttpError instead of hand-rolling one [#throw-a-ready-made-httperror-instead-of-hand-rolling-one]
Repeating `ctx.response.status = ...; return {...}` at every place a request
can fail adds up. `@arcton/core` exports `HttpError` plus an `Http`
namespace with a factory for each common status — `Http.BadRequest`,
`Http.Unauthorized`, `Http.Forbidden`, `Http.NotFound`,
`Http.MethodNotAllowed`, `Http.Conflict`, `Http.Gone`,
`Http.UnprocessableEntity`, `Http.TooManyRequests`,
`Http.InternalServerError`, `Http.ServiceUnavailable` — so the
status/message pairing lives in one place instead of at every throw site:
```ts
import { Arcton, Http } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.listen()
```
Each factory is a plain function, not a class — call it, don't `new` it. It
returns an `HttpError` (a subclass of `Error`) carrying:
* `status` — the HTTP status code (`404` for `Http.NotFound`)
* `code` — a stable, machine-readable tag (`'NOT_FOUND'`) safe for a client to
switch on, unlike `message`
* `message` — the status's reason phrase by default, overridable as the
factory's first argument
* `body` — an optional second argument: the exact value to send back instead
of the default `{ code, message }`
```ts
import { Http } from '@arcton/core'
throw Http.Conflict('Email already registered', { field: 'email' })
```
`throw Http.NotFound` — the bare function reference, with no `()` — throws
the function itself, not an `HttpError`. A catch block checking
`instanceof HttpError` won't recognize it, and it reaches the adapter as an
undifferentiated `500` instead (see [Uncaught errors](./uncaught-errors.mdx)).
Always call the factory.
On its own, throwing one of these is still an uncaught error. Catch it with
the same try/catch pattern as above, keyed off `instanceof HttpError` so the
status and body it carries drive the response:
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const catchHttpErrors: Middleware = async (ctx, next) => {
try {
await next()
} catch (err) {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
throw err
}
}
const app = Arcton()
app.use(catchHttpErrors)
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.listen()
```
A status without a named factory still works — construct `HttpError`
directly: `new HttpError(451, 'UNAVAILABLE_FOR_LEGAL_REASONS', 'Unavailable For Legal Reasons')`.
See [HTTP errors](../api/http-errors.mdx) for the full list of factories and
their default status/code/message.
## Arcton's own responses [#arctons-own-responses]
A few responses come from Arcton itself, not from your code:
* No route matches the request at all → `404` with a JSON body shaped
`{"code":"NOT_FOUND","message":"Not Found"}`, built directly from
`Http.NotFound()` — computed once, not per request, and resolved without
ever throwing (unlike a handler's own `throw Http.NotFound()`, it doesn't
depend on a registered catch-all to become a response — see
[HTTP errors](../api/http-errors.mdx)).
* A route exists for the path but not for this method → `405` with an
`Allow` header listing the methods that node does have (e.g.
`Allow: GET, POST`).
* A `params`, `query` or `body` schema rejects the request → `400` with a
JSON body shaped `{"issues":[{"message":"...","path":[...]}]}` — see
[Validation errors](../validation/validation-errors.mdx).
* The request's `Content-Type` has no parser registered for it → `415` with
an empty body — see [Body parsers](../validation/body-parsers.mdx).
* A built-in parser can't parse the body (malformed JSON, for example) →
`400` with `{"issues":[{"message":"Invalid request body"}]}`.
See [Response](../fundamentals/response.mdx) for the full mapping from a
handler's return value to a `Response`.
# Uncaught Errors (/en/docs/errors/uncaught-errors)
## A throw becomes a 500 [#a-throw-becomes-a-500]
Arcton's own pipeline — providers, middleware, validation, the handler —
never swallows an exception. If a handler, a
[provider](../providers/overview.mdx), or a custom body parser registered
with `app.parser()` throws, that error propagates all the way out to the
runtime adapter serving the request — unless the app has registered a
[global error handler](./global-error-handler.mdx), which catches it first.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/risky', () => {
throw new Error('boom')
})
app.listen()
```
A request to `/risky` here logs the error with `console.error` and responds
with a `500` — both shipped adapters behave this way. See
[Adapters](../api/adapters.mdx) for the exact mechanics on Bun and Node.
## Two errors Arcton itself can throw at request time [#two-errors-arcton-itself-can-throw-at-request-time]
A couple of Arcton's own checks throw synchronously while a response is being
built, and are uncaught the same way:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/broken', ctx => {
ctx.response.status = 999
return { ok: true }
})
app.listen()
```
Setting a status outside `[200, 599]` throws
`Invalid response status 999: must be between 200 and 599` when the response
materializes — the same 500 outcome as any other uncaught throw. Assigning to
`ctx.response.status` after the body has already finalized throws for a
different reason (`TypeError: Attempted to assign to readonly property.`) —
see the callout in [Responding with errors](./responding-with-errors.mdx).
Wrap the parts of your app that can legitimately fail — a downstream call, a
parse you don't trust — with the patterns in
[Responding with errors](./responding-with-errors.mdx), or catch everything
in one place with a [global error handler](./global-error-handler.mdx),
instead of letting them reach the adapter as a bare 500.
# Application (/en/docs/fundamentals/application)
Every Arcton app starts the same way — call `Arcton()` and you get an object
you register routes and behavior on:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.listen()
```
Every registration method — `get`, `post`, `use`, `provide`, `parser` — returns
the same app, so calls chain:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.use(async (ctx, next) => {
console.log(ctx.request.method, new URL(ctx.request.url).pathname)
await next()
})
.get('/health', () => ({ status: 'ok' }))
app.listen()
```
## Prefixing an instance [#prefixing-an-instance]
`Arcton()` takes an optional config with one field, `prefix`:
```ts
import { Arcton } from '@arcton/core'
const api = Arcton({ prefix: '/api' })
api.get('/status', () => ({ ok: true }))
api.listen()
```
`prefix` is applied to every route and `ws` route registered directly on that
instance — here, `GET /api/status`. It must be a static path (no `:param` or
`*wildcard` segment), and `'/'` behaves the same as leaving it out. The same
instance you configure a prefix on is also what you mount as a module inside
another app — see [Modules](../routing/modules.mdx).
## The app surface [#the-app-surface]
| Member | What it does |
| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `config` | the `ArctonConfig` object you passed to `Arcton()` |
| `get` / `post` / `put` / `delete` / `patch` / `head` / `options` | register a route for that HTTP method — see [HTTP Methods](../routing/http-methods.mdx) |
| `ws` | register a WebSocket route — see [WebSockets](../routing/websockets.mdx) |
| `use` | add global or path-scoped middleware, or mount a module — see [Middleware](../middleware/overview.mdx) and [Modules](../routing/modules.mdx) |
| `provide` | compose typed values onto `ctx` — see [Providers](../providers/overview.mdx) |
| `parser` | register a body parser for a `Content-Type` — see [Body Parsers](../validation/body-parsers.mdx) |
| `listen` | start the server — see [Listen Options](../configuration/listen-options.mdx) |
Each route method accepts either a handler (with optional middleware before
it) or an options object with `params` / `query` / `body` schemas — see
[Validation Overview](../validation/overview.mdx). What happens between a
request arriving and a handler running is the subject of
[Request Lifecycle](./request-lifecycle.mdx).
# Context (/en/docs/fundamentals/context)
Every middleware, provider and handler receives the same kind of object,
`ctx`. Its base shape is always there:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => {
// ctx.request → the raw Request
// ctx.params → { id: string }, inferred from the route literal
// ctx.query → Record, built from the URL's search params
// ctx.response → { status?: number; headers: Headers } until it materializes
return { id: ctx.params.id, referer: ctx.request.headers.get('referer') }
})
app.listen()
```
* `request` is the standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) — see [Request](./request.mdx).
* `params` is typed from the route literal you passed to `.get()` (or from a
`params` schema, if the route declared one) — see
[Path Parameters](../routing/path-parameters.mdx).
* `query` is `Record` by default (or a schema's output),
built lazily the first time you read it — see
[Query Parameters](../routing/query-parameters.mdx).
* `response` starts as `{ status?: number; headers: Headers }` and is what you
shape a response through before it materializes — see [Response](./response.mdx).
## Context grows with what you register [#context-grows-with-what-you-register]
`ctx.body` only appears on routes that declare a `body` schema, and any value
a `provide()` call returns is merged flat onto `ctx` — no namespace — for
everything registered after it:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app
.provide(() => ({ requestId: crypto.randomUUID() }))
.post('/users', {
body: v.object({ name: v.pipe(v.string(), v.minLength(1)) }),
handler: ctx => ({
requestId: ctx.requestId,
body: ctx.body
})
})
app.listen()
```
`ctx.requestId` is available here because the `provide()` call above it ran
first; `ctx.body` is available because this route declared a `body` schema.
Neither would be on `ctx` — or type-check — without those. See
[Providers](../providers/overview.mdx) for how `provide()` composes, and
[Body](../validation/body.mdx) for `ctx.body`.
# Request Lifecycle (/en/docs/fundamentals/request-lifecycle)
Every request an Arcton app serves goes through the same sequence of stages:
```text
match → global steps (snapshot at registration) → validate → route middleware → handler → response mapping
```
This page walks through each stage at a conceptual level and links to where
it's covered in depth.
## Match [#match]
The incoming method and pathname are matched against the route tree. A match
carries the handler chain built for that route, plus the params captured along
the way. No match falls back to a `404`; a match on the path but not the
method falls back to a `405` — see [Routing Overview](../routing/overview.mdx),
[Precedence](../routing/precedence.mdx) and [Errors](../errors/overview.mdx).
## The global-steps snapshot [#the-global-steps-snapshot]
This is the single most important thing to know about how middleware and
providers compose: **when a route is registered, it captures the `use()` and
`provide()` calls made so far.** Calls made after registration don't reach it.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/before', () => 'registered with no global steps yet')
app.use(async (ctx, next) => {
ctx.response.headers.set('X-Global', 'yes')
await next()
})
app.get('/after', () => 'registered after the middleware above')
app.listen()
```
`/before` runs with none of the surrounding `use()`/`provide()` calls, because
none existed yet when it was registered. `/after` runs wrapped by the
middleware above it, because that middleware was already registered. Reordering
the two `get()` calls relative to `use()` changes what each route runs — the
router itself never re-checks this later. See
[Execution Order](../middleware/execution-order.mdx) for the full ordering
rules, including scoped middleware and mounted modules.
## Validate [#validate]
If the route declared `params`, `query` or `body` schemas, they run in that
order against the current values, replacing `ctx.params` / `ctx.query` /
`ctx.body` with the validated (and possibly coerced) output. The first failing
schema stops the request there. See [Validation Overview](../validation/overview.mdx).
## Route middleware [#route-middleware]
Middleware passed directly to a route runs last, closest to the handler —
after every global and scoped step, after validation. See
[Route-level Middleware](../middleware/route-level.mdx).
## Handler [#handler]
The handler runs with a fully typed `ctx` — see [Context](./context.mdx) for
what's on it by this point.
## Response mapping [#response-mapping]
Whatever the handler (or an earlier step that short-circuited) returns is
mapped to an HTTP `Response`, combined with anything already set on
`ctx.response`. See [Response](./response.mdx) for the complete mapping.
# Request (/en/docs/fundamentals/request)
`ctx.request` is a standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) — everything the Fetch API gives you is available directly:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/whoami', ctx => ({
method: ctx.request.method,
userAgent: ctx.request.headers.get('user-agent'),
url: ctx.request.url
}))
app.listen()
```
## Query string and path [#query-string-and-path]
`new URL(ctx.request.url)` works if you want the raw URL, but for the common
case Arcton already gives you the parsed pieces: `ctx.query` for the search
params and `ctx.params` for path segments — see [Context](./context.mdx),
[Query Parameters](../routing/query-parameters.mdx) and
[Path Parameters](../routing/path-parameters.mdx).
## Reading the body directly [#reading-the-body-directly]
Reading `ctx.request` yourself — `.json()`, `.text()`, `.arrayBuffer()`,
`.formData()` — works the same as it would on any `Request`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/echo', async ctx => {
const payload = await ctx.request.json()
return { received: payload }
})
app.listen()
```
This is a separate path from `ctx.body`: `ctx.body` only exists on a route
that declares a `body` schema, and its value is what came out of validation,
already parsed according to the request's `Content-Type` and coerced by your
schema. See [Body](../validation/body.mdx) and
[Body Parsers](../validation/body-parsers.mdx) for that path.
# Response (/en/docs/fundamentals/response)
A handler returns whatever the response should contain, and Arcton maps it to
a `Response`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/json', () => ({ ok: true }))
app.get('/text', () => 'plain text')
app.get('/bytes', () => new Uint8Array([1, 2, 3]))
app.get('/raw', () => new Response('custom', { status: 202 }))
app.listen()
```
## The full mapping [#the-full-mapping]
| Returned | Body | Inferred `Content-Type` |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `Response` | passed through as-is; `ctx.response` is ignored entirely | — |
| `string` | the string | `text/plain; charset=UTF-8` |
| plain object or array | `JSON.stringify(...)` | `application/json; charset=UTF-8` |
| `Blob` | the blob | `blob.type`, or `application/octet-stream` when empty |
| `FormData` | the form data | none — an explicit `Content-Type` is removed so the runtime can generate its own multipart boundary |
| `URLSearchParams` | the params | none inferred (the runtime sets `application/x-www-form-urlencoded;charset=UTF-8`) |
| `ArrayBuffer`, or any view of one (`Uint8Array`, `Int32Array`, `DataView`, Node `Buffer`) | the bytes | `application/octet-stream` |
| `ReadableStream` | streamed | `application/octet-stream` |
| `null`, `undefined`, or no return | empty | none |
An explicit `ctx.response.headers.set('Content-Type', ...)` always wins over
the inferred one, with one exception:
Returning `FormData` drops any `Content-Type` you set yourself — Arcton
removes it so the runtime can generate its own
`multipart/form-data; boundary=...` header. Set other headers freely; the
boundary has to come from the runtime.
`Map` and `Set` aren't handled specially — they fall into the plain-object
branch, and `JSON.stringify` serializes them as `{}`. Return an array or plain
object built from their entries instead, e.g. `Object.fromEntries(myMap)` or
`[...mySet]`.
## Status [#status]
`ctx.response.status` sets the status; it defaults to `200`. A status outside
`200`–`599` throws `Invalid response status N: must be between 200 and 599`.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/users', ctx => {
ctx.response.status = 201
ctx.response.headers.set('Location', '/users/1')
return { id: '1' }
})
app.listen()
```
Set `ctx.response.status` before the response materializes — in the handler,
or before calling `await next()` in middleware. Setting it afterward throws,
because by then it's already part of a real `Response`, whose `status` can't
be reassigned.
`204`, `205` and `304` force an empty body: an inferred `Content-Type` is
dropped, but a `Content-Type` you set explicitly survives.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.delete('/users/:id', ctx => {
ctx.response.status = 204
})
app.listen()
```
## Setting cookies [#setting-cookies]
`ctx.response.headers` is a real `Headers` object — `.append('Set-Cookie', ...)`
adds a cookie without clobbering ones already set, so multiple cookies work by
calling it more than once. This works whether you do it in the handler or in
middleware after `await next()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.append('Set-Cookie', 'theme=dark; Path=/')
ctx.response.headers.append('Set-Cookie', 'session=abc123; HttpOnly; Path=/')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
Header mutation after `await next()` reaching the client this way — and status
only being settable before that point — comes from how `ctx.response`
materializes into a real response as the pipeline unwinds. See
[Request Lifecycle](./request-lifecycle.mdx) and
[Modifying Responses](../middleware/modifying-responses.mdx) for that
mechanism.
# Deployment (/en/docs/getting-started/deployment)
Deploying an Arcton app comes down to running one build command and then
starting the result — which command depends on which template you scaffolded.
## Bun: compile a standalone binary [#bun-compile-a-standalone-binary]
The Bun template's `compile` script bundles your app and the Bun runtime into
a single executable:
```bash
bun run compile
```
which runs:
```bash
bun build --compile --minify --sourcemap ./src/index.ts --outfile arcton-app
```
The result is a self-contained binary — no `node_modules`, no separate runtime
install on the target machine:
```bash
./arcton-app
```
If you'd rather run the source directly without compiling, the template's
`start` script does that instead:
```bash
bun run start
```
## Node.js: build then run [#nodejs-build-then-run]
The Node.js template's `build` script type-checks and emits JavaScript:
```bash
npm run build
```
which runs:
```bash
tsc --build
```
Then start the compiled output with the `start` script:
```bash
npm run start
```
which runs:
```bash
node dist/index.js
```
## Labeling the environment [#labeling-the-environment]
Pass `env` to `listen()` to label the startup banner for the environment
you're deploying to — see [Environment](../configuration/environment.mdx).
# Development (/en/docs/getting-started/development)
Both templates come with a `dev` script wired to their runtime, so the way you
start local development is the same regardless of which one you picked:
```bash
bun run dev
```
```bash
npm run dev
```
```bash
pnpm run dev
```
## What each template's `dev` script runs [#what-each-templates-dev-script-runs]
The Bun template's `dev` script is:
```bash
bun --hot src/index.ts
```
`--hot` reloads your code as files change without dropping open connections,
so you can keep iterating on routes and middleware without restarting the
process by hand.
The Node.js template's `dev` script is:
```bash
tsx watch src/index.ts
```
`tsx` runs the TypeScript entry point directly, and `watch` restarts the
process whenever a source file changes.
## Environment [#environment]
`listen()`'s `env` option only labels the startup banner it prints — it
defaults to `process.env.NODE_ENV`, falling back to `'development'` when
that's unset, which is exactly the case while running either dev script. See
[Environment](../configuration/environment.mdx) for how to set it explicitly.
# Your First Server (/en/docs/getting-started/first-server)
An Arcton application starts as a single call to `Arcton()`. Register a route
on it, then call `listen()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen()
```
Run it with `bun src/index.ts` (or `tsx src/index.ts` on Node.js) and it
listens on port 3000 by default, printing a startup banner with the URL it's
serving.
## Returning data [#returning-data]
Whatever the handler returns becomes the response body. Return a plain object
or array and it's serialized as JSON automatically:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
The full set of return types Arcton understands — strings, objects, binary
data, streams, a raw `Response` — is in [Response](../fundamentals/response.mdx).
## Reading a path parameter [#reading-a-path-parameter]
A `:param` segment in the path is captured and typed on `ctx.params`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
See [Path Parameters](../routing/path-parameters.mdx) for how segments are
matched, and [Application](../fundamentals/application.mdx) for the rest of
what an app instance can do.
## Choosing a port [#choosing-a-port]
`listen()` takes an options object:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ port: 4000 })
```
The full list of options is in [Listen Options](../configuration/listen-options.mdx).
# Installation (/en/docs/getting-started/installation)
The fastest way to start an Arcton project is the interactive scaffolder. Pick
whichever command matches the package manager you already have:
```bash
bun create arcton
```
```bash
npm create arcton
```
```bash
pnpm create arcton
```
You can also run it through the `arcton` CLI directly:
```bash
bunx arcton create my-arcton-app
```
Passing a name (`my-arcton-app` above) skips the project-name prompt.
## What the scaffold asks [#what-the-scaffold-asks]
The CLI walks through a short set of prompts:
* **Project name** — used for the folder and the generated `package.json`.
* **Runtime** — Bun or Node.js. This picks which template gets copied and
whether `@arcton/adapter-node` is added as a dependency.
* **Package manager** — bun, pnpm or npm, used only to pick the install
command it offers to run for you.
* **Install dependencies now?** — optional; you can always install later.
When it finishes, it prints the next commands to run (`cd` into the project,
install if you skipped that step, then the dev script).
## Next steps [#next-steps]
See [Project Structure](./project-structure.mdx) for what got generated,
[Your First Server](./first-server.mdx) to see the code that's already there,
and [Development](./development.mdx) to run it.
# Project Structure (/en/docs/getting-started/project-structure)
The [installation](./installation.mdx) scaffold copies one of two small
templates depending on the runtime you pick. Both are intentionally minimal —
one dependency, one source file.
## Bun template [#bun-template]
```text
my-arcton-app/
├── package.json
└── src/
└── index.ts
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen()
```
`package.json` depends on `@arcton/core` and declares three scripts —
`dev`, `start` and `compile` — covered in [Development](./development.mdx) and
[Deployment](./deployment.mdx).
## Node.js template [#nodejs-template]
```text
my-arcton-app/
├── package.json
├── tsconfig.json
└── src/
└── index.ts
```
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen({ adapter: nodeAdapter })
```
The only difference from the Bun template is the extra `@arcton/adapter-node`
dependency and the `adapter: nodeAdapter` option passed to `listen()` — see
[Runtimes](../fundamentals/application.mdx) for why that's the one line that
changes. `package.json` here declares `dev`, `build` and `start`, and
`tsconfig.json` configures the TypeScript build used by `build`.
## Growing from here [#growing-from-here]
Both templates are a normal Arcton app — everything in
[Fundamentals](../fundamentals/application.mdx),
[Routing](../routing/overview.mdx) and beyond applies directly to `src/index.ts`.
# App Config (/en/docs/configuration/app-config)
## Giving an instance a prefix [#giving-an-instance-a-prefix]
Every `Arcton()` instance takes an optional config object. It has exactly one
field: `prefix`.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api' })
app.get('/users', () => ({ users: [] }))
app.listen()
```
With `prefix: '/api'`, the route above is reachable at `GET /api/users`. The
prefix is applied to every route and `ws()` route registered directly on this
instance — you write `'/users'`, Arcton serves `/api/users`.
## Reading the config back [#reading-the-config-back]
`app.config` exposes the exact object you passed to `Arcton()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api' })
console.log(app.config.prefix) // '/api'
app.listen()
```
## Rules for `prefix` [#rules-for-prefix]
* `prefix` must be a **static path** — a `:param` or `*wildcard` segment
throws when you call `Arcton()`. See
[Registration errors](../errors/registration-errors.mdx) for the exact
error.
* `'/'` and omitting `prefix` entirely are equivalent — both mean no prefix.
* When a module (an `Arcton()` instance mounted with `app.use(module)`) has
its own prefix, the parent's prefix and the module's prefix compose. See
[Modules](../routing/modules.mdx) for how that composition works.
`prefix` only affects routes and `ws()` routes registered directly on that
instance. It has nothing to do with `use(scope, middleware)` — a scope is a
separate, unprefixed path comparison. See [Scoped
middleware](../middleware/scoped.mdx).
# Environment (/en/docs/configuration/environment)
## What `env` does [#what-env-does]
`app.listen()` takes an `env` option that defaults to
`process.env.NODE_ENV ?? 'development'`. It is used for exactly one thing: the
label printed on the startup banner.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ env: 'staging' })
```
The banner then prints `Environment staging` instead of the default. See
[Listen options](./listen-options.mdx) for the rest of what `listen()`
prints and returns.
## Reading environment variables [#reading-environment-variables]
Beyond that one label, environment variables are read the normal way for
whichever runtime is serving the app — there's no Arcton-specific config
layer to go through.
On Bun, `.env` files are loaded automatically, so `process.env` already has
whatever a `.env` file defines by the time your code runs:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
const databaseUrl = process.env.DATABASE_URL
app.get('/health', () => ({ ok: databaseUrl !== undefined }))
app.listen()
```
On Node.js, read `process.env` the same way. Load a `.env` file first if you
use one — for example with Node's own `--env-file` flag when starting the
process:
```bash
node --env-file=.env dist/index.js
```
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
const databaseUrl = process.env.DATABASE_URL
app.get('/health', () => ({ ok: databaseUrl !== undefined }))
app.listen({ adapter: nodeAdapter })
```
`NODE_ENV` isn't read for anything but the `env` default above — if your own
code branches on it (feature flags, logging verbosity, and so on), read
`process.env.NODE_ENV` directly, the same as `app.listen()` does.
# Listen Options (/en/docs/configuration/listen-options)
## Starting a server [#starting-a-server]
`app.listen()` takes an optional options object and returns a `RuntimeServer`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ port: 8080, hostname: '0.0.0.0' })
```
Every field is optional:
Calling `app.listen()` with no arguments starts on port 3000 using the Bun
adapter:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen()
```
## Picking a free port [#picking-a-free-port]
Passing `port: 0` asks the OS for a free port instead of a fixed one. Read the
actual port back from the returned server:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
const server = app.listen({ port: 0 })
console.log(server.port) // an OS-assigned port
console.log(server.url) // e.g. http://localhost:54231/
server.stop()
```
This is exactly the pattern used to test a real app end to end — see
[Testing overview](../testing/overview.mdx).
## Choosing an adapter [#choosing-an-adapter]
`adapter` selects which runtime serves the app. It defaults to `bunAdapter`.
Pass `nodeAdapter` to run on Node.js instead:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ adapter: nodeAdapter })
```
See [Adapters](../api/adapters.mdx) for what an adapter is, and
[Runtime support](../introduction/runtime-support.mdx) for the concrete
differences between the two shipped adapters.
## The startup banner and the returned server [#the-startup-banner-and-the-returned-server]
`listen()` prints a startup banner — the Arcton wordmark, followed by the
Arcton version, the runtime name and version, the environment label, and the
listening URL. The `env` option controls only that label; see
[Environment](./environment.mdx) for the details.
It returns a `RuntimeServer`:
```ts
interface RuntimeServer {
readonly port: number
readonly url: URL
stop(closeActiveConnections?: boolean): void | Promise
}
```
`stop()` returns `void` on the Bun adapter and a `Promise` on the Node
adapter, so awaiting it is always safe:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
const server = app.listen({ port: 0 })
await server.stop()
```
See [listen()](../api/listen.mdx) for the full API reference.
## Graceful shutdown [#graceful-shutdown]
By default, `listen()` drains the server on `SIGTERM`/`SIGINT` instead of
leaving termination to the runtime's default behavior: it stops accepting
new connections, waits for in-flight requests to finish (up to
`shutdownTimeout`, 10 seconds by default), then exits the process. If a
request is still running once the timeout elapses, active connections are
force-closed instead.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ shutdownTimeout: 5000 })
```
`gracefulShutdown` is intended for applications where Arcton owns the
process lifecycle — on signal, it calls `process.exit()`, which ends the
*whole* process, not just this server. Set it to `false` when the host
application manages process signals itself (e.g. Arcton embedded inside a
larger process, or a runtime where OS signals aren't meaningful):
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.listen({ gracefulShutdown: false })
```
A second `SIGTERM`/`SIGINT` received while already shutting down is
ignored — it doesn't start a second, concurrent drain.
# Better Auth (/en/docs/integrations/better-auth)
[Better Auth](https://www.better-auth.com) is a framework-agnostic
authentication library. It exposes a standard Web handler — a function that
takes a `Request` and returns a `Response` — along with a small server-side
API for reading the current session.
This guide assumes you already have an Arcton app and a configured Better
Auth instance. If you haven't set up Better Auth yet, see its own
[installation guide](https://www.better-auth.com/docs/installation). Every
example below imports that instance from a local `./auth` module — a stand-in
for yours:
```ts title="auth.ts"
declare const auth: {
handler: (request: Request) => Promise
api: {
getSession: (options: {
headers: Headers
}) => Promise<{
user: { id: string; email: string }
session: { id: string }
} | null>
}
}
export { auth }
```
## Installation [#installation]
```bash
bun add better-auth
```
```bash
npm install better-auth
```
```bash
pnpm add better-auth
```
```bash
yarn add better-auth
```
## Register the Better Auth handler [#register-the-better-auth-handler]
Better Auth's `auth.handler` takes a `Request` and returns a `Response`.
Forward every request under your auth path to it with
[`app.all()`](../routing/http-methods.mdx#every-method-on-one-path):
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { auth } from './auth'
const app = Arcton()
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
`app.all()` registers the same handler for every HTTP method Arcton
supports, so this one route answers `GET`, `POST`, and everything else
Better Auth's routes need — sign-up, sign-in, sign-out, session lookup, and
so on.
A handler can return a `Response` directly, and Arcton sends it through
unchanged, so `auth.handler`'s response reaches the client as-is. See
[Response](../fundamentals/response.mdx) for more.
`*path` is a [wildcard](../routing/path-parameters.mdx) and requires at
least one path segment, so a request to `/api/auth` on its own doesn't
match. Register it separately if your app needs to handle that exact path:
`app.all('/api/auth', ctx => auth.handler(ctx.request))`.
## CORS [#cors]
If your frontend runs on a different origin, add
[`@arcton/cors`](../middleware/cors.mdx) before the auth route, with
`credentials: true` so the session cookie is sent cross-origin. Add that
same origin to Better Auth's `trustedOrigins`:
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
import { auth } from './auth'
const app = Arcton()
app.use(
cors({
origin: 'http://localhost:3001',
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
})
)
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
See [CORS](../middleware/cors.mdx) for the full set of options.
## Accessing the session in protected routes [#accessing-the-session-in-protected-routes]
Use `auth.api.getSession()` to read the current session from the request
headers, and expose it with [`provide()`](../providers/overview.mdx) so it's
available on `ctx` for any route registered afterward:
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { auth } from './auth'
const app = Arcton()
.provide(async ctx => {
const session = await auth.api.getSession({ headers: ctx.request.headers })
return { user: session?.user ?? null, session: session?.session ?? null }
})
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.get(
'/me',
async (ctx, next) => {
if (!ctx.user) return new Response('Unauthorized', { status: 401 })
await next()
},
ctx => ({ user: ctx.user })
)
app.listen()
```
`ctx.user` and `ctx.session` are `null` when there's no active session. Add
a middleware like the one above to any route that should require
authentication — apply it per route, or scope it with `use()` over a whole
section of routes.
## Complete example [#complete-example]
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
import { auth } from './auth'
const app = Arcton()
.use(
cors({
origin: 'http://localhost:3001',
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
})
)
.provide(async ctx => {
const session = await auth.api.getSession({ headers: ctx.request.headers })
return { user: session?.user ?? null, session: session?.session ?? null }
})
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.get(
'/me',
async (ctx, next) => {
if (!ctx.user) return new Response('Unauthorized', { status: 401 })
await next()
},
ctx => ({ user: ctx.user })
)
app.get('/posts', ctx => ({ posts: [], viewer: ctx.user }))
app.listen()
```
This works the same way on Bun and Node — Arcton hands `auth.handler` a
standard `Request` on either runtime.
# Logging (/en/docs/integrations/logger)
`@arcton/logger` logs one line per request — method, path, status, duration
— with zero runtime dependencies. It's a single middleware: no
configuration lives on `Arcton()` or `listen()`.
## Installation [#installation]
```bash
bun add @arcton/logger
```
```bash
npm install @arcton/logger
```
```bash
pnpm add @arcton/logger
```
```bash
yarn add @arcton/logger
```
## Basic usage [#basic-usage]
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger())
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
Every request now produces one JSON line, once the response is known:
```json
{"level":"info","time":"2026-09-14T16:00:00.000Z","msg":"GET /users/1 200 0.4ms","method":"GET","path":"/users/1","status":200,"durationMs":0.4}
```
## Status decides the level [#status-decides-the-level]
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger())
app.get('/ok', () => ({ ok: true })) // logged at info
app.get('/missing', ctx => {
ctx.response.status = 404 // logged at warn (4xx)
return { error: 'not found' }
})
app.get('/boom', () => {
throw new Error('kaboom') // logged at error
})
app.listen()
```
A `2xx`/`3xx` response logs at `info`, a `4xx` at `warn`, a `5xx` at
`error` — no handler has to log anything itself. If a request fails with
nothing downstream catching the error, the logger logs it at `error` with
the error attached and re-throws it unchanged, so error handling (an
[`onError()`](../errors/global-error-handler.mdx) handler, or none at all)
behaves exactly as it would without the logger in place.
## Pretty mode [#pretty-mode]
`pretty: true` trades JSON for a format meant to be read live, in a
terminal — no dependency to install, no transport to configure:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger({ pretty: process.env.NODE_ENV !== 'production' }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
A request now prints two lines instead of one — `→` as it arrives, `←`
once it's done — each with the same `level` a JSON line would carry,
spelled out and colored, not just implied by color:
```text
→ INFO 16:00:00.000 GET /users/1
← INFO 16:00:00.004 200 GET /users/1 0.4ms
```
A request that fails with nothing catching the error is labeled `ERROR`
instead of a status — there isn't one, the same as the JSON line for this
case has no `status` field — with the error's message appended:
```text
→ INFO 16:00:01.000 GET /boom
← ERROR 16:00:01.001 GET /boom 0.1ms kaboom
```
`level` still gates what prints: `'silent'` prints nothing at all, and a
level above what a given request would log at (a `warn` minimum, say)
drops the `→` arrival line and any `←`/`ERR` line that doesn't clear it
either.
## Child loggers [#child-loggers]
`log.child(bindings)` returns a new logger with `bindings` merged into
every record it writes from then on — useful for tagging every line from
one part of an app without repeating those fields on every call:
```ts
import { createLogger } from '@arcton/logger'
const log = createLogger()
const dbLog = log.child({ component: 'database' })
dbLog.info('query executed', { table: 'users' })
// { "component": "database", "table": "users", "msg": "query executed", ... }
```
Children compose — a grandchild carries every binding its ancestors added.
`createLogger()` builds a standalone [`Logger`](../api/logger.mdx#logger),
independent of any request; see the [API reference](../api/logger.mdx) for
the full `trace`/`debug`/`info`/`warn`/`error`/`fatal` set.
## A custom sink [#a-custom-sink]
`sink` is where a formatted line is written — `process.stdout.write` by
default (falling back to `console.log` where `process` doesn't exist, like
a Worker). Pass your own to redirect output, for example to collect log
lines in a test:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const lines: string[] = []
const app = Arcton()
app.use(logger({ sink: line => lines.push(line) }))
app.get('/', () => 'ok')
app.listen()
```
## Logging outside the request cycle [#logging-outside-the-request-cycle]
`logger()` returns the middleware with the underlying `Logger` attached as
`.logger`, so the same logger can be used anywhere else in your app — for
example, right after `listen()`:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
const log = logger()
app.use(log)
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
log.logger.info(`listening on ${server.url}`)
```
See [`logger()`](../api/logger.mdx) for the full API reference.
# OpenAPI & Scalar (/en/docs/integrations/openapi)
`@arcton/openapi` builds an OpenAPI 3.1 document from the routes an app
actually ends up with, and serves an interactive [Scalar](https://scalar.com)
UI that reads it. There is no separate schema to maintain — the document is
generated from the same `params`/`query`/`body` schemas a route already
validates against, plus an optional `response` contract.
`@arcton/core` doesn't know this package exists. `openapi()` is an ordinary
[middleware](../middleware/overview.mdx): register it with `app.use()` and it
answers `GET /openapi.json` and `GET /docs` itself.
## Installation [#installation]
```bash
bun add @arcton/openapi
```
```bash
npm install @arcton/openapi
```
```bash
pnpm add @arcton/openapi
```
```bash
yarn add @arcton/openapi
```
## Basic usage [#basic-usage]
Register `openapi()` with `app.use()`:
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
import * as z from 'zod'
const app = Arcton()
app.get('/users/:id', {
params: z.object({ id: z.uuid() }),
response: z.object({ id: z.string(), name: z.string() }),
handler: ctx => ({ id: ctx.params.id, name: 'Ada' })
})
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' }
})
)
app.listen({ port: 3000 })
```
This serves `GET /openapi.json` (the document) and `GET /docs` (Scalar,
reading that same document — never a second copy of it).
Because it's a middleware, it runs in registration order like any other: one
registered after an auth middleware is protected by it, one registered before
is public.
## Documenting a route [#documenting-a-route]
`params`, `query`, and `body` already document themselves — whatever you
pass Arcton to validate a route is exactly what ends up in the generated
document. A `body` declared as a schema is documented as `application/json`;
declared with `content`, each media type the route accepts is documented with
its own schema — see
[Accepting specific media types](../validation/body.mdx#accepting-specific-media-types).
Two more fields, both documentation only, round out an operation:
```ts
import { Arcton } from '@arcton/core'
import * as z from 'zod'
const app = Arcton()
app.get('/users/:id', {
params: z.object({ id: z.uuid() }),
response: {
200: z.object({ id: z.string(), name: z.string() }),
404: z.object({ message: z.string() })
},
detail: {
operationId: 'getUser',
summary: 'Get user',
tags: ['Users']
},
handler: ctx => ({ id: ctx.params.id, name: 'Ada' })
})
app.listen()
```
`response` is a status → schema map; a bare schema is shorthand for `{ 200:
schema }`. `detail` maps `operationId`/`summary`/`description`/`tags`/
`deprecated` onto the OpenAPI operation. Neither is validated at runtime — a
handler that returns something else still responds exactly as it would
without them. See [`response`/`detail`](../api/arcton-app.mdx#routeoptions)
and [`RouteDetail`](../api/arcton-app.mdx#routedetail).
When `response` is omitted, the documentation still includes a generic `200`
response, but it cannot infer the returned value's shape: TypeScript types do
not exist at runtime, and executing the handler to sample it could require
context or cause side effects. Declare `response` when you want to document a
schema or specific status codes.
A declared `response` is the whole contract: `{ 404: schema }` documents only a
`404`, with no implicit `200` added.
## Schema requirements [#schema-requirements]
Converting a schema to OpenAPI relies on [Standard JSON
Schema](https://standardschema.dev/json-schema), a sibling to the [Standard
Schema](https://standardschema.dev/) interface Arcton already validates
with — Zod 4.6+ and ArkType 2.2+ implement it out of the box. Valibot doesn't
yet; wrap a schema with `toStandardJsonSchema()` from
[`@valibot/to-json-schema`](https://valibot.dev/guides/json-schema/) to opt
in.
A schema that doesn't implement it — or one whose shape has no JSON Schema
equivalent, like a Zod transform on the way out — degrades to an empty
schema (`{}`) rather than failing the build. A path parameter or a body still
appears in the document with its name and location; only its type is
unknown. A `query` schema is the exception: its parameters are listed by
reading the schema's properties, so one with no JSON Schema, or one that isn't
a plain object (a union, for example), adds no query parameters at all. See
[Standard JSON Schema](../api/validation-types.mdx#standardjsonschemav1).
## Configuring the paths [#configuring-the-paths]
Both routes are configurable, and the Scalar UI can be turned off entirely:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users', () => [])
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
document: { path: '/schema.json' },
docs: { path: '/reference' }
})
)
app.listen()
```
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users', () => [])
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
docs: false // only /openapi.json is served
})
)
app.listen()
```
## Configuring Scalar [#configuring-scalar]
Scalar's own configuration — theme, page title, which CDN serves its bundle
— is kept separate from the document's `info`/`servers`/`tags`, under `docs`:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users', () => [])
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
docs: {
pageTitle: 'Users API Reference',
configuration: { theme: 'purple' }
}
})
)
app.listen()
```
`configuration` is passed straight through to Scalar — see [Scalar's own
configuration docs](https://guides.scalar.com/scalar/scalar-api-references/configuration)
for every option it accepts. Scalar's JS bundle loads from a CDN by default;
pass `cdn` to point at a self-hosted build instead.
## Modules and the final route tree [#modules-and-the-final-route-tree]
The document reflects the app's final route tree, read the first time it's
requested — including routes pulled in through [modules](../routing/modules.mdx), correctly
prefixed:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
import * as z from 'zod'
const users = Arcton({ prefix: '/users' })
users.get('/:id', {
response: z.object({ id: z.string() }),
handler: ctx => ({ id: ctx.params.id })
})
const app = Arcton({ prefix: '/api' })
app.use(users)
app.use(openapi({ info: { title: 'API', version: '1.0.0' } }))
app.listen()
// documents GET /api/users/{id}
```
A wildcard route (`*rest`) has no OpenAPI path-template equivalent and is
left out of the document, and a [`ws()`](../api/arcton-app.mdx#ws) route has
no contract to document in the first place — both keep serving normally,
they just don't appear at `/openapi.json`.
See [`openapi()`](../api/openapi.mdx) for the full API reference.
# Architecture Overview (/en/docs/introduction/architecture-overview)
An Arcton application has four layers. This page is the map; each layer has a
deeper page under [Architecture](../architecture/overview.mdx).
```text
Bun / Node.js the runtime
│
RuntimeAdapter @arcton/adapter-bun | @arcton/adapter-node
│ Request
▼
route tree match method + pathname
│ handler + params
▼
pipeline (steps) middleware · providers · validation
│ returned value
▼
response mapping value → Response
```
## The adapter owns the runtime [#the-adapter-owns-the-runtime]
`listen()` hands the adapter one `fetch`-style function and a list of
WebSocket routes. The adapter starts a real server, converts whatever the
runtime uses into a standard `Request`, and writes the `Response` back.
Because that is the whole contract, the same application runs on Bun or on
Node.js by changing one option:
```ts
import { Arcton } from '@arcton/core'
import { nodeAdapter } from '@arcton/adapter-node'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.listen({ adapter: nodeAdapter })
```
## The router matches paths [#the-router-matches-paths]
Routes are stored in a tree. Each node holds a map of static children plus one
dynamic slot and one wildcard slot, so following a path is a series of direct
lookups rather than a scan over a list of patterns.
Matching tries static, then dynamic, then wildcard, and backtracks when a
branch dead-ends. See [Precedence](../routing/precedence.mdx) for what that
means when you write overlapping routes, and [Router](../architecture/router.mdx)
for why the tree is shaped this way.
## The pipeline is resolved when you register [#the-pipeline-is-resolved-when-you-register]
When you register a route, Arcton captures the middleware and providers that
exist at that moment and stores the finished chain with the route. Nothing is
re-resolved per request, and no request-time lookup can change which middleware
a route runs.
The order inside that chain is always:
```text
global middleware → validation → route middleware → handler
```
with each middleware wrapping the next, so post-`next()` code unwinds in
reverse. See [Execution order](../middleware/execution-order.mdx).
## Responses are mapped from values [#responses-are-mapped-from-values]
Whatever the handler returns is mapped to a `Response`: objects to JSON,
strings to text, binary types to `application/octet-stream`, a `Response`
straight through. `ctx.response` carries the status and headers accumulated
along the way. See [Response](../fundamentals/response.mdx).
## Modules merge into one tree [#modules-merge-into-one-tree]
`app.use(module)` grafts a module's route tree into the parent's tree at
registration time, combining prefixes and wrapping the mounted handlers with
the parent's middleware. After mounting there is one tree and one lookup per
request, no matter how the application was organized in source.
See [Modules](../routing/modules.mdx) and
[Module composition](../architecture/module-composition.mdx).
## Packages [#packages]
| Package | Role |
| ---------------------- | ------------------------------------------------------ |
| `@arcton/core` | `Arcton()`, routing, pipeline, response mapping |
| `@arcton/contracts` | the types both sides share, including `RuntimeAdapter` |
| `@arcton/adapter-bun` | serves on Bun |
| `@arcton/adapter-node` | serves on Node.js |
| `@arcton/cors` | CORS middleware |
| `arcton` | the CLI that scaffolds a project |
# Philosophy (/en/docs/introduction/philosophy)
Arcton makes a handful of opinionated choices. Knowing them makes the rest of
the API predictable.
## Registration order is the semantics [#registration-order-is-the-semantics]
Most frameworks treat the order of `use()` calls as a hint. In Arcton it is the
rule, applied consistently: a route runs the middleware and providers that were
registered **before it**, and nothing else.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/first', () => 'no timing header')
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set('X-Time', `${performance.now() - start}ms`)
})
app.get('/second', () => 'timed')
app.listen()
```
`/first` and `/second` have different pipelines, and the file reads top to
bottom exactly as it behaves. The same rule governs `provide()`, path-scoped
middleware, and mounting a module — one idea instead of four.
[Execution order](../middleware/execution-order.mdx) covers this in depth.
## Types come from what you wrote [#types-come-from-what-you-wrote]
Arcton derives types from the code you already typed rather than asking you to
declare them twice. The route literal produces `ctx.params`. A schema produces
the validated shape of `ctx.body`. A provider widens the context for
everything after it.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ startedAt: Date.now() }))
.get('/uptime/:unit', ctx => ({
unit: ctx.params.unit,
uptime: Date.now() - ctx.startedAt
}))
app.listen()
```
Nothing above names a type, and everything in it is typed.
## Values, not response objects [#values-not-response-objects]
A handler returns a value. Arcton maps it to a `Response`. There is no
`res.send()` to forget and no double-send to debug, and a handler stays an
ordinary function that returns data — which is what makes it easy to test.
When a route needs headers, a status code, or a stream, `ctx.response` and a
returned `Response` are both available.
## Composition over configuration [#composition-over-configuration]
Behavior comes from composing small pieces: a middleware, a provider, a module.
There is no plugin registry to learn — a reusable feature is a function that
returns a middleware, which is exactly how [`@arcton/cors`](../middleware/cors.mdx)
is built.
## The core does not know the runtime [#the-core-does-not-know-the-runtime]
`@arcton/core` never imports a Bun or Node.js API. Everything the framework
needs from a runtime is described by the `RuntimeAdapter` interface in
`@arcton/contracts`, and an adapter implements it. That keeps the routing and
middleware code identical across runtimes, and makes supporting a new one a
matter of writing one file.
See [Runtime abstraction](../architecture/runtime-abstraction.mdx).
## Work is done at registration time [#work-is-done-at-registration-time]
Arcton prefers to do work once, when routes are registered, rather than on
every request. Each route stores its own resolved pipeline. Mounting a module
merges its route tree into the parent's instead of chaining routers.
`ctx.query` is parsed only if something reads it.
The result is that a request does the minimum: match a path, run a prepared
chain, map a value.
## Explicit over implicit [#explicit-over-implicit]
Arcton avoids magic that is convenient once and confusing later. There is no
namespace where framework values hide — provided values sit directly on the
context. A scope is a static path, not a second pattern language. Conflicting
routes throw at registration instead of silently shadowing each other.
# Runtime Support (/en/docs/introduction/runtime-support)
The same application runs on Bun and on Node.js. Which runtime serves it is
decided by the adapter you pass to `listen()`.
## Bun [#bun]
Bun is the default. Passing no adapter uses `bunAdapter`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ runtime: 'bun' }))
app.listen({ port: 3000 })
```
Run it with `bun src/index.ts`. To be explicit, import the adapter yourself:
```ts
import { bunAdapter } from '@arcton/adapter-bun'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ runtime: 'bun' }))
app.listen({ adapter: bunAdapter })
```
## Node.js [#nodejs]
Install `@arcton/adapter-node`:
```bash
bun add @arcton/adapter-node
```
```bash
npm install @arcton/adapter-node
```
```bash
pnpm add @arcton/adapter-node
```
```bash
yarn add @arcton/adapter-node
```
Then pass it to `listen()`:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ runtime: 'node' }))
app.listen({ adapter: nodeAdapter })
```
Everything else — routes, middleware, providers, validation, response mapping
— behaves identically. Only the adapter changes.
## What both adapters do [#what-both-adapters-do]
* Serve the application over HTTP and expose the bound `port` and `url`.
* Convert the runtime's native request into a standard `Request`, and write a
standard `Response` back.
* Upgrade [WebSocket routes](../routing/websockets.mdx) registered with
`app.ws()`.
* Log an error thrown out of the request handler with `console.error` and
answer `500`.
## Differences worth knowing [#differences-worth-knowing]
| | Bun | Node.js |
| ----------------- | --------------------- | ------------------------------------------- |
| Package | `@arcton/adapter-bun` | `@arcton/adapter-node` |
| `adapter.version` | `Bun.version` | the Node.js version without the leading `v` |
| `server.stop()` | returns immediately | returns a promise to await |
`stop()` is the one that shows up in code. On Node.js, await it:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'ok')
const server = app.listen({ adapter: nodeAdapter })
process.on('SIGTERM', async () => {
await server.stop()
})
```
## Choosing a port [#choosing-a-port]
`port` defaults to `3000`. Passing `0` binds a free port, which is how tests
avoid collisions — read the real value back from the server:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
console.log(`listening on ${server.url}`)
```
See [Testing](../testing/overview.mdx) for the full pattern.
## Other runtimes [#other-runtimes]
`RuntimeAdapter` is a public interface in `@arcton/contracts`: a `name`, a
`version`, a `capabilities` object and a `serve()` function. Any runtime that
can accept a `Request` and return a `Response` can back one. See
[Runtime types](../api/runtime-types.mdx) and
[Adapters](../architecture/adapters.mdx).
# What is Arcton? (/en/docs/introduction/what-is-arcton)
Arcton is a framework for building HTTP APIs in TypeScript. An application is
an `Arcton()` instance: you register routes on it, compose behavior around
them, and start it with `listen()`.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
app.listen({ port: 3000 })
```
That is a complete, runnable file. `bun src/index.ts` serves it.
## Handlers return values [#handlers-return-values]
A handler returns whatever the response should contain. Arcton maps the
returned value to an HTTP response: an object becomes JSON, a string becomes
`text/plain`, a `Uint8Array` becomes a binary body.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/json', () => ({ ok: true }))
app.get('/text', () => 'plain text')
app.get('/empty', () => {})
app.listen()
```
When you need full control, return a `Response` and Arcton passes it through
untouched. The complete mapping is in [Response](../fundamentals/response.mdx).
## The route literal types the context [#the-route-literal-types-the-context]
Arcton reads the path you wrote and types `ctx.params` from it:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:userId/posts/:postId', ctx => {
// ctx.params is { userId: string; postId: string }
return { user: ctx.params.userId, post: ctx.params.postId }
})
app.listen()
```
Misspelling `ctx.params.userID` is a compile error, not a runtime `undefined`.
## Context grows as you compose [#context-grows-as-you-compose]
`provide()` attaches values to the context and widens its type for everything
registered afterwards:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(ctx => ({
requestId: ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
}))
.get('/whoami', ctx => ({ requestId: ctx.requestId }))
app.listen()
```
`ctx.requestId` is typed on the handler because the provider was registered
before the route. See [Providers](../providers/overview.mdx).
## Applications are built from modules [#applications-are-built-from-modules]
A module is an `Arcton()` instance with its own prefix. Mounting one merges its
routes into the parent's route tree:
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/', () => [{ id: '1' }])
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton({ prefix: '/api' })
app.use(users)
app.listen()
```
This serves `GET /api/users` and `GET /api/users/:id`. See
[Modules](../routing/modules.mdx).
## Runtimes [#runtimes]
The core has no dependency on any specific runtime. Bun and Node.js are both
supported through adapters, selected at `listen()`:
```ts
import { Arcton } from '@arcton/core'
import { nodeAdapter } from '@arcton/adapter-node'
const app = Arcton()
app.get('/', () => 'Hello from Node.js')
app.listen({ adapter: nodeAdapter })
```
See [Runtime support](./runtime-support.mdx).
## What Arcton includes [#what-arcton-includes]
* A route tree with static, dynamic and wildcard segments and defined
[precedence](../routing/precedence.mdx).
* [Middleware](../middleware/overview.mdx) that is global, path-scoped or
attached to a single route.
* Per-route [validation](../validation/overview.mdx) of params, query and body
through [Standard Schema](https://standardschema.dev/), so Zod, Valibot and
ArkType all work.
* [Body parsing](../validation/body-parsers.mdx) by `Content-Type`, extensible
with your own parsers.
* [WebSocket routes](../routing/websockets.mdx).
* [CORS](../middleware/cors.mdx) as a separate package.
* Bun and Node.js [adapters](../api/adapters.mdx), and the `RuntimeAdapter`
interface behind them.
# When to Use Arcton (/en/docs/introduction/when-to-use)
Arcton is aimed at TypeScript HTTP services where the shape of a request
matters: typed parameters, validated input, and an application that grows into
modules without turning into a pile of routers.
## Good fits [#good-fits]
**JSON APIs.** Handlers return values and Arcton serializes them, so a CRUD
endpoint is a function that returns an object.
**Services with validated input.** Params, query and body each take a
[Standard Schema](https://standardschema.dev/), and the validated output is
what reaches the handler, already coerced and typed.
**Applications organized by domain.** Each area of the app is a module with its
own prefix, developed in its own file and mounted into the parent — see
[Modules](../routing/modules.mdx).
**Projects that care about the request path.** The route tree, the resolved
per-route pipeline and the lazy query parsing all move work to registration
time.
**Code that should run on more than one runtime.** The application is written
against Arcton; Bun or Node.js is an argument to `listen()`.
**Realtime alongside HTTP.** `app.ws()` registers WebSocket routes on the same
server as the HTTP routes.
## Conceptual comparisons [#conceptual-comparisons]
These are analogies to orient you, not compatibility claims. Arcton has its own
API, and code does not port over unchanged.
**Coming from Express.** Middleware will feel familiar: a function that
receives the request context and a `next` it can await, with code after
`await next()` running on the way out. Two things differ. Handlers return a
value instead of calling a `res` method, and `use()` applies to the routes
registered after it rather than to everything in the file. See
[Execution order](../middleware/execution-order.mdx).
**Coming from Hono or Elysia.** The value-returning handler and the
runtime-adapter model will look familiar. Arcton derives `ctx.params` from the
route literal in the same spirit, keeps provided values flat on the context
through [`provide()`](../providers/overview.mdx), and merges modules into a
single route tree at registration.
**Coming from NestJS.** The unit of organization is a module here too, but it
is a plain `Arcton()` instance rather than a class with decorators, and
`provide()` composes typed context per request instead of resolving a
dependency graph. If you want constructor injection and decorators, that is a
different model than the one Arcton offers.
**Coming from Fastify.** Schema-driven validation will feel natural.
Arcton accepts any Standard Schema library rather than a specific one, and the
schema's output type flows into the handler.
## What to expect from pre-1.0 [#what-to-expect-from-pre-10]
Arcton is pre-1.0 and the API can change between releases. Pin your
dependencies and read the release notes before upgrading.
## Next [#next]
# CORS (/en/docs/middleware/cors)
Install `@arcton/cors`:
```bash
bun add @arcton/cors
```
```bash
npm install @arcton/cors
```
```bash
pnpm add @arcton/cors
```
```bash
yarn add @arcton/cors
```
Then register it as global middleware:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(cors())
app.get('/users', () => [{ id: '1' }])
app.listen()
```
With no options the middleware allows any origin. Register it before your
routes, so every route below is covered — see
[Execution order](./execution-order.mdx).
## Allowing specific origins [#allowing-specific-origins]
`origin` accepts a string, an array, or a function:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(cors({ origin: 'https://app.example.com' }))
app.get('/users', () => [{ id: '1' }])
app.listen()
```
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: ['https://app.example.com', 'https://admin.example.com']
})
)
app.get('/users', () => [{ id: '1' }])
app.listen()
```
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: origin => origin.endsWith('.example.com')
})
)
app.get('/users', () => [{ id: '1' }])
app.listen()
```
The function receives the request's origin and the `Request` itself, so a
decision can depend on the path or on a header.
When the allowed origin is anything other than `'*'`, the matching origin is
echoed back and `Vary: Origin` is appended, so caches key the response by
origin. A request whose origin is not allowed continues to your route with no
CORS headers added, and the browser blocks the result on the client side.
## Options [#options]
| Option | Default | Effect |
| ---------------- | ------------------ | ------------------------------------------------- |
| `origin` | `'*'` | which origins are allowed |
| `methods` | echoes the request | `Access-Control-Allow-Methods` on preflight |
| `allowedHeaders` | echoes the request | `Access-Control-Allow-Headers` on preflight |
| `exposedHeaders` | — | `Access-Control-Expose-Headers` on the response |
| `credentials` | `false` | adds `Access-Control-Allow-Credentials` |
| `maxAge` | — | `Access-Control-Max-Age` on preflight, in seconds |
| `preflight` | `true` | whether to answer preflight requests |
## Credentialed requests [#credentialed-requests]
Browsers reject a credentialed response that allows every origin, so name the
origins you trust:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: 'https://app.example.com',
credentials: true,
exposedHeaders: ['X-Total-Count']
})
)
app.get('/users', ctx => {
ctx.response.headers.set('X-Total-Count', '1')
return [{ id: '1' }]
})
app.listen()
```
Combining `origin: '*'` with `credentials: true` throws a `TypeError` when
`cors()` is called, at startup rather than on the first request.
## Preflight [#preflight]
A browser sends `OPTIONS` with `Access-Control-Request-Method` before certain
cross-origin requests. `cors()` answers those itself with `204` and the
computed headers:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: 'https://app.example.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 600
})
)
app.post('/users', () => ({ created: true }))
app.listen()
```
With `methods` or `allowedHeaders` omitted, the preflight response echoes what
the request asked for.
Only a real preflight is intercepted — an `OPTIONS` request without
`Access-Control-Request-Method` passes through to
[your own `app.options()` route](../routing/http-methods.mdx).
## Covering every response [#covering-every-response]
Because `cors()` is global middleware, its headers also reach the `404` and
`405` responses Arcton generates, which is what a browser needs in order to
report the real status instead of a CORS failure. See
[Global middleware](./global.mdx).
## Scoping it [#scoping-it]
To apply CORS to one section only, give it a scope:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use('/public', cors({ origin: '*' }))
app.get('/public/status', () => ({ ok: true }))
app.get('/internal/status', () => ({ ok: true }))
app.listen()
```
A [scoped](./scoped.mdx) registration covers matched routes under that path.
See [`cors()` in the API reference](../api/cors.mdx) for the full signature.
# Execution Order (/en/docs/middleware/execution-order)
Two rules explain every ordering question in Arcton:
1. **A route runs the middleware and providers registered before it.**
2. **Inside that set, the order is** global → validation → route middleware →
handler.
## The registration snapshot [#the-registration-snapshot]
When you register a route, Arcton takes the middleware and providers that exist
at that moment and stores the finished chain with the route. Calls made
afterwards do not reach it.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/before', () => ({ timed: false }))
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set('X-Time', `${performance.now() - start}ms`)
})
app.get('/after', () => ({ timed: true }))
app.listen()
```
`/after` gets the `X-Time` header. `/before` does not — it was registered when
that middleware did not exist yet.
This is why the file reads the way it behaves: move a `use()` call up or down
and you change exactly the routes below it.
The practical rule: register global middleware and providers at the top of
the file, before any route. Then every route sees all of them.
## The order inside a request [#the-order-inside-a-request]
For a matched route:
```text
request
│
▼
┌─ match path + method ───────────────┐
│ │
▼ │
global middleware (in registration order, outermost first)
│ │
▼ │
validation (params → query → body)
│ │
▼ │
route middleware (in the order written, innermost)
│ │
▼ │
handler │
│ │
└─ unwind: route mw → global mw ──────┘
│
▼
response mapping
```
Seen in code:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.use(async (ctx, next) => {
console.log('1 global in')
await next()
console.log('6 global out')
})
app.get('/users/:id', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
middleware: [
async (ctx, next) => {
console.log('3 route in')
await next()
console.log('5 route out')
}
],
handler: ctx => {
console.log('4 handler')
return { id: ctx.params.id }
}
})
app.listen()
```
`GET /users/42` logs `1 global in`, then validation runs (step 2, silently),
then `3 route in`, `4 handler`, `5 route out`, `6 global out`.
Because validation sits between them, global middleware sees the raw string
`ctx.params.id`, while route middleware and the handler see the number.
## Providers follow the same rule [#providers-follow-the-same-rule]
[`provide()`](../providers/overview.mdx) shares the sequence with `use()`, so
the same snapshot applies:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ startedAt: Date.now() }))
.get('/uptime', ctx => ({ uptime: Date.now() - ctx.startedAt }))
app.listen()
```
Registering the route before the provider would be a compile error, because
`ctx.startedAt` would not be part of the context type yet. The type system and
the runtime agree here: they read the same list, in the same order.
## Scoped middleware [#scoped-middleware]
A [scope](./scoped.mdx) is applied on top of the snapshot: when a route is
registered, Arcton keeps the scoped middleware whose path the route sits under,
and drops the rest.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
console.log('global')
await next()
})
app.use('/admin', async (ctx, next) => {
console.log('admin only')
await next()
})
app.get('/admin/stats', () => ({ users: 42 })) // both
app.get('/health', () => ({ status: 'ok' })) // global only
app.listen()
```
The decision happens once, at registration. Nothing is re-checked per request.
## The exception: 404 and 405 [#the-exception-404-and-405]
Responses that Arcton generates because nothing matched behave differently:
**global middleware runs on them regardless of registration order.**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('Access-Control-Allow-Origin', '*')
})
app.listen()
```
`GET /missing` answers `404` **with** the CORS header, even though the
middleware was registered after every route.
The reason is that the snapshot rule is about a route: "before" and "after"
only mean something relative to a route's own registration. A `404` has no
route, so there is nothing to be before or after — and the concerns that belong
on those responses (CORS, logging, request ids) are exactly the ones that must
cover every response. Arcton collects the unscoped `use()` middleware once when
`listen()` is called and applies it there.
What does **not** run on `404`/`405`:
| | Matched route | `404` / `405` |
| ------------------------ | ------------------------ | ------------- |
| `use(middleware)` | before-only | always |
| `use(scope, middleware)` | before-only, under scope | no |
| route middleware | yes | no |
| `provide()` | before-only | no |
| validation | yes | no |
## Modules [#modules]
Mounting a [module](../routing/modules.mdx) follows the same rule from the
parent's side: the parent's global middleware and providers registered before
`app.use(module)` wrap every route the module brings in, and anything
registered after does not.
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.use(async (ctx, next) => {
ctx.response.headers.set('X-Before', 'yes')
await next()
})
app.use(users)
app.use(async (ctx, next) => {
ctx.response.headers.set('X-After', 'no')
await next()
})
app.listen()
```
`GET /users/1` carries `X-Before` and not `X-After`.
The module's own middleware keeps working after mounting, and runs inside the
parent's.
## Why it works this way [#why-it-works-this-way]
Resolving the chain once, at registration, means a request never asks "which
middleware applies here?" — the answer was computed when the route was created.
It also makes the type system honest: `ctx` is typed from the providers
registered before the handler, which is exactly the set that will run.
See [Pipeline](../architecture/pipeline.mdx) for how the chain is built.
# Global Middleware (/en/docs/middleware/global)
`app.use(middleware)` applies a middleware to every route registered after the
call:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
console.log(`→ ${ctx.request.method} ${new URL(ctx.request.url).pathname}`)
await next()
})
app.get('/', () => ({ ok: true }))
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
Both routes log. Register global middleware near the top of the file, before
the routes it should cover — see [Execution order](./execution-order.mdx).
## Several middleware [#several-middleware]
Call `use()` once per middleware. They nest in registration order, so the first
one registered is the outermost:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set('X-Time', `${performance.now() - start}ms`)
})
app.use(async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
await next()
})
app.get('/', () => ({ ok: true }))
app.listen()
```
## It also covers 404 and 405 [#it-also-covers-404-and-405]
Global middleware runs on the responses Arcton generates when no route matches
the path, or when the path matches but the method does not:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('Access-Control-Allow-Origin', '*')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
`GET /missing` answers `404` **with** the `Access-Control-Allow-Origin` header.
That is what makes global middleware the right place for concerns that must
cover every HTTP response — CORS headers, request logging, response timing.
On `404` and `405`, global middleware runs regardless of where it sits
relative to your routes: a `use()` written after every route still applies.
A matched route, by contrast, only runs the middleware registered before it.
[Execution order](./execution-order.mdx) explains why the two rules differ.
[Scoped middleware](./scoped.mdx) and
[route middleware](./route-level.mdx) do not run on those responses, because
there is no matched route for them to belong to.
## Reading the request [#reading-the-request]
The context carries the standard `Request`, so anything you can do with the
Fetch API is available:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const auth = ctx.request.headers.get('authorization')
if (auth === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
Global middleware runs before [validation](../validation/overview.mdx), so it
sees raw values: `ctx.params` and `ctx.query` are still strings there, even on
a route whose schema converts them.
## Adding values to the context [#adding-values-to-the-context]
When a middleware exists to compute a value the handler needs, use
[`provide()`](../providers/overview.mdx) instead — it puts the value on the
context and types it for everything registered afterwards.
# Modifying Responses (/en/docs/middleware/modifying-responses)
`ctx.response` carries the status and headers that will be used for the
response. Middleware can read and change it on the way in and on the way out:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('X-Powered-By', 'Arcton')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
## Headers [#headers]
`ctx.response.headers` is a standard `Headers` object. `set()` replaces,
`append()` adds another value:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
ctx.response.headers.append('Set-Cookie', 'session=abc; Path=/; HttpOnly')
ctx.response.headers.append('Set-Cookie', 'theme=dark; Path=/')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
Header changes work both before and after `await next()`, and both send the
cookies above. Setting a header the handler also sets means the later write
wins, so a middleware running after `next()` can override the handler.
## Status [#status]
Set `ctx.response.status` before the body is produced — in the handler, or in
a middleware before `await next()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/users', ctx => {
ctx.response.status = 201
ctx.response.headers.set('Location', '/users/42')
return { id: '42' }
})
app.listen()
```
The status is fixed once the response body is produced. Assigning
`ctx.response.status` after `await next()` throws a `TypeError`. To change a
status on the way out, return a new value or a `Response` instead — see
below.
## Replacing the body after next() [#replacing-the-body-after-next]
Returning a value after `await next()` replaces the body. The headers and
status accumulated so far carry over:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
return { wrapped: true, at: new Date().toISOString() }
})
app.get('/', () => ({ ok: true }))
app.listen()
```
The client receives the wrapper object.
To replace the status as well, return a `Response`. It wins outright — no
headers are merged in from `ctx.response`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
if (ctx.response.headers.get('X-Deprecated') === 'yes') {
return new Response(JSON.stringify({ error: 'gone' }), {
status: 410,
headers: { 'content-type': 'application/json' }
})
}
})
app.get('/legacy', ctx => {
ctx.response.headers.set('X-Deprecated', 'yes')
return { ok: true }
})
app.listen()
```
## Short-circuiting [#short-circuiting]
Returning a value **without** calling `next()` answers the request immediately,
and nothing further in the chain runs:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
if (ctx.request.headers.get('x-api-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
A short-circuit can also return a plain value, which is mapped the same way a
handler's return value is:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
if (!ctx.request.headers.has('authorization')) {
ctx.response.status = 401
return { error: 'missing authorization' }
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
## Caching and conditional responses [#caching-and-conditional-responses]
Because middleware sees the response on the way out, it can add cache headers
across a whole section of the API:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/static', async (ctx, next) => {
await next()
ctx.response.headers.set('Cache-Control', 'public, max-age=3600')
})
app.get('/static/config', () => ({ theme: 'dark' }))
app.listen()
```
## Complete example [#complete-example]
Timing, a request id and cookies together:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const start = performance.now()
const requestId = ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
await next()
ctx.response.headers.set('X-Request-Id', requestId)
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
})
app.get('/', ctx => {
ctx.response.status = 200
ctx.response.headers.append('Set-Cookie', 'visited=1; Path=/')
return { ok: true }
})
app.listen()
```
For how a returned value becomes a `Response`, see
[Response](../fundamentals/response.mdx).
# Middleware Overview (/en/docs/middleware/overview)
A middleware is a function that runs around your handlers. It receives the
[context](../fundamentals/context.mdx) and a `next` function, and it decides
what happens before and after the rest of the chain:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
})
app.get('/', () => ({ ok: true }))
app.listen()
```
Everything before `await next()` runs on the way in. Everything after runs on
the way out, once the handler and every inner middleware have finished.
## The onion [#the-onion]
Middleware nests. With two registered, the flow through a request is:
```text
┌── middleware A ─────────────────────────┐
│ ┌── middleware B ──────────────────┐ │
│ │ ┌── handler ───────────────┐ │ │
│ │ │ returns a value │ │ │
│ │ └──────────────────────────┘ │ │
│ │ code after await next() │ │
│ └──────────────────────────────────┘ │
│ code after await next() │
└─────────────────────────────────────────┘
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
console.log('A: in')
await next()
console.log('A: out')
})
app.use(async (ctx, next) => {
console.log('B: in')
await next()
console.log('B: out')
})
app.get('/', () => {
console.log('handler')
return { ok: true }
})
app.listen()
```
A request to `/` logs `A: in`, `B: in`, `handler`, `B: out`, `A: out`.
## Three ways to attach one [#three-ways-to-attach-one]
| Form | Applies to |
| ------------------------------------ | ----------------------------------------------------------------- |
| `app.use(middleware)` | every route registered after the call, plus `404`/`405` responses |
| `app.use('/admin', middleware)` | routes under that path, registered after the call |
| `app.get(path, middleware, handler)` | that route only |
```ts
import { Arcton } from '@arcton/core'
import type { Middleware } from '@arcton/contracts'
const requestId: Middleware = async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
await next()
}
const app = Arcton()
app.use(requestId) // global
app.use('/admin', requestId) // scoped
app.get('/health', requestId, () => ({ ok: true })) // route level
app.listen()
```
Each form has its own page: [Global](./global.mdx), [Scoped](./scoped.mdx) and
[Route level](./route-level.mdx).
Which middleware a route runs is decided when the route is registered, from
the calls made before it. [Execution order](./execution-order.mdx) is the
page to read once the basics are clear.
## Short-circuiting [#short-circuiting]
A middleware that returns a value without calling `next()` answers the request
on its own. The handler and everything inside never run:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
if (ctx.request.headers.get('x-api-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
The returned value goes through the same
[response mapping](../fundamentals/response.mdx) as a handler's, so returning
an object produces JSON and returning a `Response` passes it through.
## Typing a middleware [#typing-a-middleware]
`Middleware` is exported from `@arcton/contracts`. Declaring the type gives a
standalone middleware its parameter types:
```ts
import type { Middleware } from '@arcton/contracts'
export const logger: Middleware = async (ctx, next) => {
const { method, url } = ctx.request
console.log(`→ ${method} ${new URL(url).pathname}`)
await next()
}
```
That is a fragment — import it into a file that builds an app to run it.
## Reusable middleware [#reusable-middleware]
A middleware that takes options is just a function that returns one:
```ts
import type { Middleware } from '@arcton/contracts'
export function requireHeader(name: string): Middleware {
return async (ctx, next) => {
if (!ctx.request.headers.has(name)) {
return new Response(`Missing ${name}`, { status: 400 })
}
await next()
}
}
```
That is the same shape [`@arcton/cors`](./cors.mdx) uses.
# Route Middleware (/en/docs/middleware/route-level)
Pass middleware before the handler to attach it to one route:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get(
'/reports',
async (ctx, next) => {
if (ctx.request.headers.get('authorization') === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
},
() => ({ reports: [] })
)
app.listen()
```
The last argument is always the handler; everything before it is middleware,
running in the order written. Any number can be passed:
```ts
import { Arcton } from '@arcton/core'
import type { Middleware } from '@arcton/contracts'
const authenticate: Middleware = async (ctx, next) => {
if (ctx.request.headers.get('authorization') === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
}
const audit: Middleware = async (ctx, next) => {
await next()
console.log(`audited ${new URL(ctx.request.url).pathname}`)
}
const app = Arcton()
app.delete('/users/:id', authenticate, audit, ctx => ({
deleted: ctx.params.id
}))
app.listen()
```
## Route middleware is typed by its route [#route-middleware-is-typed-by-its-route]
A middleware written inline gets the route's parameter types:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get(
'/users/:id',
async (ctx, next) => {
console.log(`looking up user ${ctx.params.id}`)
await next()
},
ctx => ({ id: ctx.params.id })
)
app.listen()
```
A middleware declared separately as `Middleware` is reusable across routes and
sees `ctx.params` as `Record`.
## With the options form [#with-the-options-form]
When a route uses the [options form](../validation/overview.mdx), the
middleware goes in the `middleware` array:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
body: v.object({
item: v.string(),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
middleware: [
async (ctx, next) => {
console.log(`order for user ${ctx.params.id}: ${ctx.body.item}`)
await next()
}
],
handler: ctx => ({ userId: ctx.params.id, order: ctx.body })
})
app.listen()
```
Route middleware runs **after** validation, so it sees the validated,
converted values: `ctx.params.id` is a number here, and `ctx.body` is typed
from the schema.
## Where it sits in the chain [#where-it-sits-in-the-chain]
Route middleware is the innermost layer, closest to the handler:
```text
global middleware → validation → route middleware → handler
```
So a global middleware wraps a route middleware, which wraps the handler. See
[Execution order](./execution-order.mdx).
Because route middleware belongs to a matched route, it does not run on the
`404` and `405` responses Arcton generates.
## Choosing a form [#choosing-a-form]
| Use | When |
| ---------------------- | ---------------------------------------------- |
| Route middleware | one or two routes need the behavior |
| [Scoped](./scoped.mdx) | a whole section of the API needs it |
| [Global](./global.mdx) | every response needs it, including `404`/`405` |
# Scoped Middleware (/en/docs/middleware/scoped)
Passing a path before the middleware limits it to the routes under that path:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/admin/stats', () => ({ users: 42 }))
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
`/admin/stats` is protected. `/health` is not.
## What "under a path" means [#what-under-a-path-means]
A scope matches the path itself and anything below it, compared segment by
segment — not as a string prefix:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/api', async (ctx, next) => {
ctx.response.headers.set('X-Scoped', 'yes')
await next()
})
app.get('/api', () => ({ root: true })) // matches the scope itself
app.get('/api/users', () => ({ users: [] })) // matches, nested
app.get('/apidocs', () => ({ docs: true })) // does NOT match
app.listen()
```
`/apidocs` starts with the same letters as `/api`, but it is not under it.
## A scope is a static path [#a-scope-is-a-static-path]
Scopes are plain paths — `:param` and `*wildcard` segments are not part of this
form:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/users', async (ctx, next) => {
ctx.response.headers.set('X-Section', 'users')
await next()
})
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
The scope `'/users'` covers `/users/:id` because that route lives under it. See
[Registration errors](../errors/registration-errors.mdx) for the error a
non-static scope produces.
## Order still applies [#order-still-applies]
Like global middleware, a scope only reaches routes registered after it:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/admin/early', () => ({ guarded: false }))
app.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/admin/late', () => ({ guarded: true }))
app.listen()
```
Only `/admin/late` is guarded. Register the scope before the routes it
protects — see [Execution order](./execution-order.mdx).
## Scoped middleware and matched routes [#scoped-middleware-and-matched-routes]
Scoped middleware runs only for routes that matched. It does not run on the
`404` and `405` responses Arcton generates, since those have no route to belong
to. When a concern has to reach every response, register it
[globally](./global.mdx) instead.
## Scopes inside modules [#scopes-inside-modules]
A [module](../routing/modules.mdx) can scope its own middleware, and the scope
is compared against the path as written inside the module — not the mounted
path:
```ts
import { Arcton } from '@arcton/core'
const api = Arcton({ prefix: '/api' })
api.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
api.get('/admin/stats', () => ({ users: 42 }))
const app = Arcton()
app.use(api)
app.listen()
```
The route is served at `/api/admin/stats` and the scope is written `'/admin'`,
matching how the route was written inside the module.
A scope belongs to the instance it is registered on. A parent's scoped
middleware does not reach the routes of a mounted module — put the scoped
middleware in the module that owns those routes.
# Providers Overview (/en/docs/providers/overview)
`provide()` composes typed context: it runs a function per request and merges
whatever it returns flat onto `ctx`, typed, for everything registered after
it:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(ctx => ({
requestId: ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
}))
.get('/whoami', ctx => ({ requestId: ctx.requestId }))
app.listen()
```
`ctx.requestId` type-checks on the handler above because `.get()` is chained
directly onto the value `.provide()` returns — that's the object whose type
actually carries `requestId`. See
[Typed Context](./typed-context.mdx) for exactly why the chaining matters.
## Providers can build on each other [#providers-can-build-on-each-other]
Providers run in registration order, and a later one can read what an earlier
one added:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ db: { query: async (_sql: string) => [] } }))
.provide(async ctx => {
const users = await ctx.db.query('select * from users')
return { users }
})
.get('/users', ctx => ctx.users)
app.listen()
```
## What you can't provide [#what-you-cant-provide]
Re-providing a key that's already on `ctx` — one you provided earlier, or one
of the base fields `request`, `params`, `query`, `response`, `body` — is a
compile error, not something checked at runtime.
Providers run before validation and route middleware, and don't run for
`404`/`405` responses. For how `provide()` composes typed context in more
depth, see [Typed Context](./typed-context.mdx); for when to reach for
`provide()` versus `use()`, see
[Providers vs Middleware](./providers-vs-middleware.mdx).
# Providers vs Middleware (/en/docs/providers/providers-vs-middleware)
`provide()` and `use()` both run per request, in registration order, and both
can be mixed freely — but they exist for different jobs.
A provider has no `next` and can't short-circuit; what it returns is merged
onto `ctx` and the chain always continues. Middleware receives `next`, runs
code before and after calling it, and can short-circuit by returning a value
without calling `next()` at all — stopping everything downstream, including
any provider or handler that would otherwise run.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.use(async (ctx, next) => {
console.log(ctx.request.method, new URL(ctx.request.url).pathname)
await next()
})
.provide(ctx => {
const authHeader = ctx.request.headers.get('authorization')
return {
user: authHeader === 'secret' ? { id: 1, name: 'Alice' } : null
}
})
.get(
'/profile',
async (ctx, next) => {
if (!ctx.user) return new Response('Unauthorized', { status: 401 })
await next()
},
ctx => ({ user: ctx.user })
)
app.listen()
```
The logging `use()` at the top just observes the request; it doesn't add
anything to `ctx`'s type. The `provide()` call attaches `user`, typed, to
everything registered after it. The route middleware on `/profile` is the
piece that can actually reject the request — returning `401` and never
calling `next()` — something a provider has no mechanism to do at all.
Reach for `provide()` when you're attaching a typed value everything
downstream should be able to read. Reach for `use()` when you need to run code
around the rest of the chain, inspect or replace the response, or stop the
request early. See [Providers Overview](./overview.mdx) and
[Middleware Overview](../middleware/overview.mdx) for each on its own.
# Typed Context (/en/docs/providers/typed-context)
Every `provide()` call returns a new app value whose type carries the added
field, for whatever gets registered on *that returned value* afterward:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/before', () => {
// ctx has no `user` here — the provide() below hasn't run yet
// in registration order
return { ok: true }
})
.provide(ctx => ({
user: ctx.request.headers.get('authorization') ? { id: 1 } : null
}))
.get('/after', ctx => ({ user: ctx.user }))
app.listen()
```
`ctx.user` type-checks on `/after` and not on `/before`, because `/after` is
registered on the value `.provide()` returned, and `/before` is registered on
the value before it.
`provide()` doesn't retroactively widen the type of an `app` you already have
— it hands back a new, wider-typed one. Registering anything that needs a
provided value has to happen on that returned value, whether by chaining like
the example above or by reassigning, e.g. `app = app.provide(...)` with `app`
declared `let`. Calling `.provide()` and then continuing to register routes
as separate statements on the original `const app` won't type-check, even
though the value is present on `ctx` at runtime either way.
## Flat, not namespaced [#flat-not-namespaced]
A provided value sits directly on `ctx` — there's no wrapper object to reach
through:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ user: { id: 1, name: 'Alice' } }))
.get('/me', ctx => ctx.user)
app.listen()
```
## Reserved keys [#reserved-keys]
A `provide()` call can't reuse a key that's already there. That includes the
base `Context` fields — `request`, `params`, `query`, `response`, `body` — and
any key a previous `provide()` in the chain already added. Both are enforced
at the type level: reusing one is a compile error.
See [Providers Overview](./overview.mdx) for the request-by-request mechanics,
and [Context](../fundamentals/context.mdx) for the base fields a provided
value sits alongside.
# HTTP Methods (/en/docs/routing/http-methods)
Each HTTP method has its own registration method:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.post('/users', () => ({ created: true }))
app.put('/users/:id', ctx => ({ replaced: ctx.params.id }))
app.patch('/users/:id', ctx => ({ updated: ctx.params.id }))
app.delete('/users/:id', ctx => ({ deleted: ctx.params.id }))
app.head('/users/:id', () => {})
app.options('/users', () => {})
app.listen()
```
The seven available are `get`, `post`, `put`, `delete`, `patch`, `head` and
`options`. They behave identically apart from the method they answer, and all
of them accept the same two call shapes — a handler with optional
[route middleware](../middleware/route-level.mdx), or an
[options object](../validation/overview.mdx) with schemas.
## Several methods on one path [#several-methods-on-one-path]
Register them one at a time. Because every call returns the app, a resource
reads as a block:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/users/:id', ctx => ({ id: ctx.params.id }))
.put('/users/:id', ctx => ({ replaced: ctx.params.id }))
.delete('/users/:id', ctx => ({ deleted: ctx.params.id }))
app.listen()
```
Registering the same method and path twice throws at registration — see
[Registration errors](../errors/registration-errors.mdx).
## Every method on one path [#every-method-on-one-path]
`app.all()` registers the same handler for all seven methods above in one
call. It's mainly for delegating a whole path — often a wildcard subtree — to
an external Request/Response handler, e.g. mounting a library like
[better-auth](https://www.better-auth.com):
```ts
import { Arcton } from '@arcton/core'
declare const auth: { handler: (request: Request) => Promise }
const app = Arcton()
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
`all` isn't a wildcard for arbitrary or non-standard HTTP verbs — it expands
to exactly the same seven methods `get`/`post`/etc. answer. A request with
some other verb still gets `405` (if the path matches something else) or
`404`.
Because it shares the same handler across all seven methods, registering
`all()` and then a specific method on the same path — in either order —
throws the same "Duplicate route" error as registering that method twice;
see [Registration errors](../errors/registration-errors.mdx). And like a
wildcard segment anywhere else, `/api/auth/*path` needs at least one segment
to match — a bare `/api/auth` needs its own registration too, if you need it.
## Method not allowed [#method-not-allowed]
When a request's path matches but its method has no handler, Arcton answers
`405` with an `Allow` header listing the methods that path does answer:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.post('/users/:id', ctx => ({ updated: ctx.params.id }))
app.listen()
```
`DELETE /users/42` returns `405` with `Allow: GET, POST` and an empty body.
The path that answers is the most specific one that matched, and matching does
not continue past it looking for another pattern that supports the method —
[Precedence](./precedence.mdx) works through the consequences.
## HEAD and OPTIONS [#head-and-options]
Both are ordinary methods here: they answer when you register them.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.head('/users/:id', ctx => {
ctx.response.headers.set('Content-Type', 'application/json')
})
app.options('/users/:id', ctx => {
ctx.response.status = 204
ctx.response.headers.set('Allow', 'GET, HEAD, OPTIONS')
})
app.listen()
```
For cross-origin preflight requests, [`@arcton/cors`](../middleware/cors.mdx)
handles the `OPTIONS` exchange for you, and it only intercepts requests that
carry `Access-Control-Request-Method` — so an `app.options()` route you
register for your own purposes keeps working alongside it.
## Choosing a status code [#choosing-a-status-code]
A handler answers `200` unless you say otherwise. Set `ctx.response.status`
before returning:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/users', ctx => {
ctx.response.status = 201
ctx.response.headers.set('Location', '/users/42')
return { id: '42' }
})
app.delete('/users/:id', ctx => {
ctx.response.status = 204
})
app.listen()
```
`204`, `205` and `304` always send an empty body, whatever the handler returns.
See [Response](../fundamentals/response.mdx).
# Modules (/en/docs/routing/modules)
A module is an `Arcton()` instance with a prefix. Mounting it with `use()`
merges its routes into the parent:
```ts title="users.ts"
import { Arcton } from '@arcton/core'
export const users = Arcton({ prefix: '/users' })
users.get('/', () => [{ id: '1' }])
users.get('/:id', ctx => ({ id: ctx.params.id }))
users.post('/', () => ({ created: true }))
```
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { users } from './users'
const app = Arcton({ prefix: '/api' })
app.use(users)
app.listen()
```
That serves `GET /api/users`, `GET /api/users/:id` and `POST /api/users`.
A module is not a special type. It is an application — the same methods, the
same middleware, the same validation. What makes it a module is that something
else mounts it.
## Prefixes compose [#prefixes-compose]
The path a route ends up at is the parent prefix, then the module prefix, then
the route path:
```text
'/api' + '/users' + '/:id' → /api/users/:id
```
A prefix must be a static path; `:param` and `*wildcard` segments throw when
the instance is created. `Arcton({ prefix: '/' })` is the same as no prefix.
## Mounting merges the route tree [#mounting-merges-the-route-tree]
`app.use(module)` copies the module's routes into the parent's route tree at
the moment you call it. After mounting there is one tree, and a request costs
one lookup no matter how many modules the application was assembled from.
Two consequences follow from merging at registration time:
* Routes registered on the module **after** it was mounted do not appear in the
parent. Mount a module once it is fully built — typically as the last thing
the parent file does.
* A collision surfaces immediately. If mounting would produce a method and path
the parent already has, registration throws, the same as registering a
duplicate route directly.
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.use(users) // throws: Duplicate route: GET /users/:id is already registered
app.listen()
```
## Middleware and mounting [#middleware-and-mounting]
The parent's global middleware and providers registered **before** the mount
wrap every route the module brings in. Anything registered after does not reach
it — the same registration-order rule that governs
[middleware](../middleware/execution-order.mdx) everywhere else.
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
})
app.use(users) // every route the module brings in gets the header
app.listen()
```
Each instance is typed on its own, so a module's handlers see the context that
module declares. When a module's handlers need a typed value, the module
declares the provider itself:
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users
.provide(ctx => ({
requestId: ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
}))
.get('/:id', ctx => ({ id: ctx.params.id, requestId: ctx.requestId }))
const app = Arcton()
app.use(users)
app.listen()
```
A module keeps its own middleware too, including path-scoped middleware, which
keeps comparing against the module-local path — the path as written inside the
module, not the mounted one:
```ts
import { Arcton } from '@arcton/core'
const api = Arcton({ prefix: '/api' })
api.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
api.get('/admin/stats', () => ({ users: 1 }))
api.get('/public', () => ({ ok: true }))
const app = Arcton()
app.use(api)
app.listen()
```
The scope is written `'/admin'`, matching the route as written inside the
module, while the route is served at `/api/admin/stats`.
A parent's path-scoped middleware does not reach a mounted module. Put the
scoped middleware inside the module it belongs to, or use global middleware
on the parent.
## Nesting [#nesting]
Modules mount modules, to any depth:
```ts
import { Arcton } from '@arcton/core'
const posts = Arcton({ prefix: '/posts' })
posts.get('/:postId', ctx => ({ post: ctx.params.postId }))
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
users.use(posts)
const app = Arcton({ prefix: '/api' })
app.use(users)
app.listen()
```
This serves `GET /api/users/:id` and `GET /api/users/posts/:postId`.
## WebSocket routes travel too [#websocket-routes-travel-too]
A [WebSocket route](./websockets.mdx) registered inside a module picks up both
prefixes when mounted:
```ts
import { Arcton } from '@arcton/core'
const chat = Arcton({ prefix: '/chat' })
chat.ws('/room', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
const app = Arcton({ prefix: '/api' })
app.use(chat)
app.listen()
```
The socket is served at `/api/chat/room`.
## Organizing a real application [#organizing-a-real-application]
A common layout is one module per domain, each owning its routes and the
middleware they need:
```text
src/
├── index.ts # creates the app, mounts modules, calls listen()
├── users/
│ └── index.ts # export const users = Arcton({ prefix: '/users' })
└── orders/
└── index.ts # export const orders = Arcton({ prefix: '/orders' })
```
```ts title="src/index.ts" no-check
import { Arcton } from '@arcton/core'
import { orders } from './orders'
import { users } from './users'
const app = Arcton({ prefix: '/api' })
app.use(async (ctx, next) => {
console.log(`${ctx.request.method} ${new URL(ctx.request.url).pathname}`)
await next()
})
app.use(users)
app.use(orders)
app.listen({ port: 3000 })
```
The logging middleware is registered before the mounts, so it covers every
route both modules bring in.
See [Module composition](../architecture/module-composition.mdx) for why
merging happens at registration.
# Routing Overview (/en/docs/routing/overview)
Register a route by calling the method you want to answer:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users', () => [{ id: '1' }])
app.post('/users', () => ({ created: true }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
Every registration method returns the app, so calls chain:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/health', () => ({ status: 'ok' }))
.get('/version', () => ({ version: '1.0.0' }))
app.listen()
```
Seven methods are available: `get`, `post`, `put`, `delete`, `patch`, `head`
and `options`. See [HTTP methods](./http-methods.mdx).
## Three kinds of segment [#three-kinds-of-segment]
A path is split on `/`, and each segment is one of three kinds:
| Segment | Written | Matches |
| -------- | ------- | --------------------------------------------------- |
| Static | `users` | exactly that text |
| Dynamic | `:id` | any single segment, captured as `ctx.params.id` |
| Wildcard | `*path` | the rest of the path, captured as `ctx.params.path` |
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/health', () => ({ status: 'ok' })) // static
app.get('/users/:id', ctx => ({ id: ctx.params.id })) // dynamic
app.get('/files/*path', ctx => ({ path: ctx.params.path })) // wildcard
app.listen()
```
`GET /files/docs/readme.md` gives `ctx.params.path === 'docs/readme.md'`.
Captured values are typed from the path you wrote — see
[Path parameters](./path-parameters.mdx). When more than one route could match
a request, [Precedence](./precedence.mdx) decides.
## Rules for a route path [#rules-for-a-route-path]
These are checked when the route is registered, so a mistake throws at startup
rather than serving a surprise later.
* A path must start with `/`.
* A path must not contain `//`.
* A parameter name must start with a letter and contain only letters, digits
and `_`.
* A wildcard must be the last segment.
* The same parameter name cannot appear twice in one path.
* The same method and path cannot be registered twice.
* Two routes cannot use different parameter names in the same slot at the same
position — `'/users/:id'` and `'/users/:userId'` conflict.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.get('/users/:id/posts', ctx => ({ user: ctx.params.id })) // same name, fine
app.listen()
```
The exact messages are listed in
[Registration errors](../errors/registration-errors.mdx).
## Trailing slashes [#trailing-slashes]
Empty segments are discarded before matching, so a trailing slash and a
repeated slash resolve to the same route:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'me')
app.listen()
```
`GET /users/me`, `GET /users/me/` and `GET /users//me` all reach that handler.
## Handlers [#handlers]
A handler receives the [context](../fundamentals/context.mdx) and returns the
response body. It can be sync or async:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/sync', () => ({ ok: true }))
app.get('/async', async () => {
const data = await Promise.resolve({ ok: true })
return data
})
app.listen()
```
Destructuring works when you only need part of the context:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ({ params }) => ({ id: params.id }))
app.listen()
```
## Beyond a single file [#beyond-a-single-file]
Routes can carry their own [middleware](../middleware/route-level.mdx) and
[validation schemas](../validation/overview.mdx), and an application can be
split into [modules](./modules.mdx) that merge into one route tree.
# Path Parameters (/en/docs/routing/path-parameters)
A `:name` segment captures one path segment:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
`GET /users/42` returns `{"id":"42"}`.
## Types come from the path [#types-come-from-the-path]
Arcton reads the route literal and types `ctx.params` from it. No generic
argument is involved:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/orgs/:orgId/repos/:repoId', ctx => {
// ctx.params is { orgId: string; repoId: string }
return { org: ctx.params.orgId, repo: ctx.params.repoId }
})
app.listen()
```
Reading a name the path does not declare is a compile error. A route with no
parameters has no parameter keys to read.
Inference needs a literal. If the path comes from a variable typed as
`string`, `ctx.params` falls back to `Record`. Passing the
path inline keeps the precise type.
## Parameter values are strings [#parameter-values-are-strings]
Every captured value is a string, because that is what a URL carries. To work
with a number, convert it — or declare a schema and let validation produce the
converted value:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/users/:id', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
handler: ctx => ({ id: ctx.params.id, type: typeof ctx.params.id })
})
app.listen()
```
`GET /users/42` now returns `{"id":42,"type":"number"}`. See
[Params and query](../validation/params-and-query.mdx).
## Wildcards [#wildcards]
A `*name` segment captures everything left in the path, joined with `/`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/files/*path', ctx => ({ path: ctx.params.path }))
app.listen()
```
| Request | `ctx.params.path` |
| ---------------------------- | --------------------- |
| `/files/readme.md` | `readme.md` |
| `/files/docs/api/index.html` | `docs/api/index.html` |
A wildcard must be the last segment of the path, and it needs at least one
segment to match: with only `/files/*path` registered, `GET /files` and
`GET /files/` produce a `404`. Register `/files` separately if you want to
answer it.
Because a wildcard accepts any remainder, validate the captured value before
using it to reach anything on disk:
```ts
import { Arcton } from '@arcton/core'
const files: Record = {
'readme.md': '# Arcton',
'docs/intro.md': 'Welcome'
}
const app = Arcton()
app.get('/files/*path', ctx => {
const segments = ctx.params.path.split('/')
if (segments.some(segment => segment === '..' || segment === '')) {
return new Response('Invalid path', { status: 400 })
}
const content = files[ctx.params.path]
if (content === undefined) {
return new Response('Not found', { status: 404 })
}
return new Response(content, { headers: { 'content-type': 'text/plain' } })
})
app.listen()
```
## Percent-encoded values [#percent-encoded-values]
Captured values are percent-decoded; the static parts of the path are matched
as written. `GET /users/hello%20world` gives `ctx.params.id === 'hello world'`.
A value whose escape sequence is malformed is handed to you exactly as it
arrived rather than failing the request.
## Multiple parameters [#multiple-parameters]
Any number of dynamic segments can appear in one path, as long as their names
differ:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/:year/:month/:slug', ctx => ({
year: ctx.params.year,
month: ctx.params.month,
slug: ctx.params.slug
}))
app.listen()
```
A dynamic and a wildcard segment can also share a path, with the wildcard last:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id/files/*path', ctx => ({
user: ctx.params.id,
path: ctx.params.path
}))
app.listen()
```
## Same position, same name [#same-position-same-name]
Routes that share a prefix must agree on the parameter name in each position:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.get('/users/:id/posts', ctx => ({ user: ctx.params.id }))
app.listen()
```
Writing `'/users/:userId/posts'` alongside `'/users/:id'` throws at
registration, because one position would capture under two names. See
[Registration errors](../errors/registration-errors.mdx).
# Route Precedence (/en/docs/routing/precedence)
When more than one route could match a request, Arcton follows two rules:
**static beats dynamic beats wildcard**, applied one segment at a time, with
backtracking when a branch dead-ends.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'the current user')
app.get('/users/:id', ctx => `user ${ctx.params.id}`)
app.get('/users/*path', ctx => `anything else: ${ctx.params.path}`)
app.listen()
```
| Request | Wins | Why |
| ------------------ | -------------- | -------------------------------------------- |
| `GET /users/me` | `/users/me` | a static segment is tried first |
| `GET /users/42` | `/users/:id` | no static `42`, so the dynamic slot takes it |
| `GET /users/a/b/c` | `/users/*path` | more segments than `:id` can hold |
Registration order does not matter. Moving `/users/me` to the bottom of the
file changes nothing — precedence is a property of the path, not of when you
wrote it.
## Matching walks the path [#matching-walks-the-path]
Arcton stores routes in a tree, one node per segment. At each node it tries the
static child first, then the dynamic slot, then the wildcard slot.
For `GET /users/42` against the routes above:
```text
/users/42
├─ "users" → static child exists ✓ descend
└─ "42" → static child "me"? ✗
dynamic slot ":id"? ✓ capture id="42", descend
node has a GET handler ✓ match
```
## Backtracking [#backtracking]
If a branch matches for a while and then dead-ends, Arcton backs out and tries
the next slot at the point where it still had options, discarding whatever
parameters that abandoned branch captured.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/a/:b/c', ctx => `deep: ${ctx.params.b}`)
app.get('/a/*rest', ctx => `rest: ${ctx.params.rest}`)
app.listen()
```
| Request | Result |
| ------------ | ------------------------------------------------------------------- |
| `GET /a/x/c` | `deep: x` — the dynamic branch reaches `c` and matches |
| `GET /a/x/y` | `rest: x/y` — `y` is not `c`, so matching backs out to the wildcard |
The `b` captured on the way into the abandoned branch is discarded, so the
handler that finally runs never sees a parameter from a path that did not
match.
## A method mismatch ends the search [#a-method-mismatch-ends-the-search]
Backtracking applies to *paths*, not to methods. Once matching reaches a node
that has handlers, that node answers — with the handler for this method if it
has one, and with `405` if it does not. Arcton does not keep looking for
another path pattern that happens to support the method.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'the current user')
app.post('/users/:id', ctx => `updated ${ctx.params.id}`)
app.listen()
```
| Request | Response |
| ---------------- | ----------------------- |
| `GET /users/me` | `200` |
| `POST /users/42` | `200` |
| `POST /users/me` | `405` with `Allow: GET` |
`POST /users/me` reaches the `/users/me` node, which only answers `GET`, so it
returns `405` — even though `/users/:id` would have accepted the `POST`.
The most specific path that matches is the one that answers. If a static path
should accept the same methods as the dynamic route beside it, register those
methods on the static path too.
Making the example above answer both:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'the current user')
app.post('/users/me', () => 'updated the current user')
app.post('/users/:id', ctx => `updated ${ctx.params.id}`)
app.listen()
```
## No match at all [#no-match-at-all]
When no path in the tree matches, the response is `404` with a
`{ code: 'NOT_FOUND', message: 'Not Found' }` JSON body — see
[HTTP errors](../api/http-errors.mdx). Global middleware still runs on it,
which is how logging and CORS headers reach those responses — see
[Global middleware](../middleware/global.mdx).
## Wildcards need something to capture [#wildcards-need-something-to-capture]
A wildcard matches one or more segments, never zero:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/files', () => 'the index')
app.get('/files/*path', ctx => `file: ${ctx.params.path}`)
app.listen()
```
Without that first route, `GET /files` would be a `404`, because `*path` has
nothing to capture.
# Query Parameters (/en/docs/routing/query-parameters)
Query parameters arrive on `ctx.query`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/search', ctx => ({
term: ctx.query.q,
page: ctx.query.page
}))
app.listen()
```
`GET /search?q=arcton&page=2` returns `{"term":"arcton","page":"2"}`.
## Values are strings, and may be missing [#values-are-strings-and-may-be-missing]
`ctx.query` is a `Record`. A key that was not sent is
`undefined`, so handle absence explicitly:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/search', ctx => {
const term = ctx.query.q ?? ''
const page = Number(ctx.query.page ?? '1')
return { term, page }
})
app.listen()
```
Two details worth knowing:
* A key sent without a value is an empty string: `?debug` gives
`ctx.query.debug === ''`.
* A key sent more than once keeps the last value: `?tag=a&tag=b` gives
`ctx.query.tag === 'b'`.
The query string is parsed the first time something reads `ctx.query`, so a
handler that never touches it pays nothing.
## Validating and converting [#validating-and-converting]
Converting by hand gets repetitive once a route takes more than one parameter.
A `query` schema does the conversion and typing in one place:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/search', {
query: v.object({
q: v.string(),
page: v.optional(
v.pipe(v.string(), v.transform(Number), v.number()),
'1'
)
}),
handler: ctx => ({ term: ctx.query.q, page: ctx.query.page })
})
app.listen()
```
`ctx.query.page` is a `number` here, and a request missing `q` is answered with
`400` before the handler runs. See
[Params and query](../validation/params-and-query.mdx) and
[Validation errors](../validation/validation-errors.mdx).
## Reading the raw query string [#reading-the-raw-query-string]
`ctx.request.url` is always available when you need the URL itself — for
repeated keys you want to keep, for example:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/filter', ctx => {
const url = new URL(ctx.request.url)
const tags = url.searchParams.getAll('tag')
return { tags }
})
app.listen()
```
`GET /filter?tag=a&tag=b` returns `{"tags":["a","b"]}`.
Query parameters are not part of route matching. `/search` and
`/search?q=x` reach the same route, and two routes cannot be distinguished by
their query string.
# WebSockets (/en/docs/routing/websockets)
`app.ws()` registers a WebSocket route on the same server as your HTTP routes:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
app.listen({ port: 3000 })
```
A client connecting to `ws://localhost:3000/chat` is upgraded automatically.
Everything else on the server keeps working over HTTP.
## The handler [#the-handler]
`message` is the only required callback. `open`, `close` and `drain` are
optional:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
open(ws) {
ws.send('connected')
},
message(ws, message) {
ws.send(`echo: ${message}`)
},
close(ws, code, reason) {
console.log('closed', code, reason)
},
drain(ws) {
console.log('socket ready for more data')
}
})
app.listen()
```
| Callback | Called when |
| ------------------------- | ------------------------------------------------------------- |
| `message(ws, message)` | a frame arrives — `string` for text, `ArrayBuffer` for binary |
| `open(ws)` | the connection has been established |
| `close(ws, code, reason)` | the connection closed |
| `drain(ws)` | a backpressured socket can accept more data |
Each callback may be async.
## The socket [#the-socket]
The `ws` value passed to every callback offers two methods:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
if (message === 'bye') {
ws.close(1000, 'client said bye')
return
}
ws.send(`echo: ${message}`)
}
})
app.listen()
```
`send()` accepts a string, an `ArrayBuffer` or a typed array. `close()` takes
an optional code and reason.
## Text and binary frames [#text-and-binary-frames]
`message` is a `string` for text frames and an `ArrayBuffer` for binary ones,
so narrow before using it:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/upload', {
message(ws, message) {
if (typeof message === 'string') {
ws.send(`text of length ${message.length}`)
return
}
ws.send(`binary of ${message.byteLength} bytes`)
}
})
app.listen()
```
## Sockets in modules [#sockets-in-modules]
A WebSocket route registered inside a [module](./modules.mdx) picks up the
prefixes when it is mounted:
```ts
import { Arcton } from '@arcton/core'
const chat = Arcton({ prefix: '/chat' })
chat.ws('/room', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
const app = Arcton({ prefix: '/api' })
app.use(chat)
app.listen()
```
The socket is served at `/api/chat/room`.
## Runtime support [#runtime-support]
WebSocket routes need an adapter that supports them; both the Bun and the
Node.js adapters do. The check happens when you call `listen()`, not when you
register the route — mounting a module can still add WebSocket routes after a
`ws()` call, so `listen()` is the first moment the complete set is known.
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
app.listen({ adapter: nodeAdapter })
```
## How ws routes differ from HTTP routes [#how-ws-routes-differ-from-http-routes]
WebSocket routes are matched by exact path — `:param` and `*wildcard` segments
belong to HTTP routes. They are also served directly by the adapter rather than
through the HTTP pipeline, so a socket connection does not run
[middleware](../middleware/overview.mdx), [providers](../providers/overview.mdx)
or [validation](../validation/overview.mdx), and the callbacks receive the
socket rather than a [context](../fundamentals/context.mdx).
To gate a connection, check inside `open` and close the socket when the check
fails:
```ts
import { Arcton } from '@arcton/core'
const rooms = new Set(['general', 'random'])
const app = Arcton()
app.ws('/room', {
open(ws) {
ws.send('joined')
},
message(ws, message) {
const room = String(message)
if (!rooms.has(room)) {
ws.close(1008, 'unknown room')
return
}
ws.send(`welcome to ${room}`)
}
})
app.listen()
```
## Connecting from a client [#connecting-from-a-client]
```ts
const socket = new WebSocket('ws://localhost:3000/chat')
socket.addEventListener('open', () => {
socket.send('hello')
})
socket.addEventListener('message', event => {
console.log(event.data)
})
```
# Testing (/en/docs/testing/overview)
Arcton apps are tested with [`bun:test`](https://bun.sh/docs/cli/test), the same runner the framework itself uses. There is no separate test client or mocking layer to learn — you exercise the real thing.
## Two techniques [#two-techniques]
* **Routes** — start a real server on an ephemeral port with `app.listen({ port: 0 })`, hit it with the platform `fetch`, then call `server.stop()`. This runs the full pipeline (middleware, providers, validation, the handler) exactly as it runs in production. See [Testing routes](./testing-routes.mdx).
* **Middleware** — a [`Middleware`](../api/middleware-types.mdx) is a plain `(ctx, next) => ...` function, so it can be called directly with a hand-built `ctx` and a fake `next`, with no server involved. See [Testing middleware](./testing-middleware.mdx).
Reach for the first when you want to confirm behavior end to end (routing, status codes, headers, response bodies). Reach for the second when you want to test one piece of middleware in isolation, independent of any particular route.
# Testing Middleware (/en/docs/testing/testing-middleware)
A [`Middleware`](../api/middleware-types.mdx) is nothing more than a `(ctx, next) => ...` function. That means it can be tested directly, without a server or a route — build a minimal `ctx` by hand, pass a fake `next`, and assert on what the middleware did.
## A `makeCtx` helper [#a-makectx-helper]
```ts
import type { Context } from '@arcton/contracts'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
```
This builds the minimum `Context` a middleware needs: the incoming `request`, empty `params`/`query`, and a fresh `response` with empty `Headers`. Reuse it for any middleware under test, not just one specific to your app.
## Testing a middleware that calls `next()` [#testing-a-middleware-that-calls-next]
```ts
import { expect, test } from 'bun:test'
import type { Context } from '@arcton/contracts'
import { cors } from '@arcton/cors'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
test('cors adds Access-Control-Allow-Origin for an allowed origin', async () => {
const middleware = cors({ origin: 'https://app.example.com' })
const ctx = makeCtx(
new Request('http://localhost/', {
headers: { origin: 'https://app.example.com' }
})
)
await middleware(ctx, async () => {})
expect(ctx.response.headers.get('Access-Control-Allow-Origin')).toBe(
'https://app.example.com'
)
})
```
## Testing a middleware that short-circuits [#testing-a-middleware-that-short-circuits]
A middleware that returns a value without calling `next()` short-circuits the pipeline. Assert that `next` was never invoked and inspect the returned value directly:
```ts
import { expect, test } from 'bun:test'
import type { Context } from '@arcton/contracts'
import { cors } from '@arcton/cors'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
test('a real preflight short-circuits with a 204 Response', async () => {
const middleware = cors({ origin: 'https://app.example.com' })
const ctx = makeCtx(
new Request('http://localhost/users', {
method: 'OPTIONS',
headers: {
origin: 'https://app.example.com',
'access-control-request-method': 'POST'
}
})
)
let nextCalled = false
const result = await middleware(ctx, async () => {
nextCalled = true
})
expect(nextCalled).toBe(false)
expect(result).toBeInstanceOf(Response)
expect((result as Response).status).toBe(204)
})
```
## Testing your own middleware [#testing-your-own-middleware]
The same technique applies to any middleware you write, not just a built-in one:
```ts
import { expect, test } from 'bun:test'
import type { Context, Middleware } from '@arcton/contracts'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
const withRequestId: Middleware = async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', 'test-id')
await next()
}
test('withRequestId sets a header before calling next', async () => {
const ctx = makeCtx(new Request('http://localhost/'))
let nextCalled = false
await withRequestId(ctx, async () => {
nextCalled = true
})
expect(nextCalled).toBe(true)
expect(ctx.response.headers.get('X-Request-Id')).toBe('test-id')
})
```
`Context` is imported as a type from `@arcton/contracts`. This tests the middleware function in isolation, decoupled from routing and the rest of the pipeline — for an end-to-end test that runs a middleware as part of a real request, see [Testing routes](./testing-routes.mdx).
# Testing Routes (/en/docs/testing/testing-routes)
The reliable way to test a route is to run the real app on a real (ephemeral) port and hit it with a real `fetch` call. Nothing is mocked — matching, middleware, providers, validation and the handler all run exactly as they would in production.
## The basic shape [#the-basic-shape]
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
test('GET /health returns ok', async () => {
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
const server = app.listen({ port: 0 })
const res = await fetch(new URL('/health', server.url))
expect(await res.json()).toEqual({ status: 'ok' })
server.stop()
})
```
`port: 0` asks the runtime for a free port instead of a fixed one, so tests can run concurrently without colliding. `server.url` is a real `URL` — pass it straight to `fetch`, or resolve a path against it with `new URL(path, server.url)`. Always call `server.stop()` once the test is done so the port is released.
## Testing a 404 [#testing-a-404]
A path with no matching route responds `404` with a `{ code: 'NOT_FOUND', message: 'Not Found' }` JSON body (see [HTTP errors](../api/http-errors.mdx)) — worth asserting directly:
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
test('an unmatched path responds 404', async () => {
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
const server = app.listen({ port: 0 })
const res = await fetch(new URL('/missing', server.url))
expect(res.status).toBe(404)
server.stop()
})
```
## Testing validation [#testing-validation]
A route with a `body`, `query` or `params` schema responds `400` with a JSON `{ issues: [...] }` body on the first validation failure. This example uses [Valibot](https://valibot.dev):
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
test('an invalid body responds 400 with issues', async () => {
const app = Arcton()
app.post('/orders', {
body: v.object({ item: v.string(), quantity: v.number() }),
handler: ctx => ctx.body
})
const server = app.listen({ port: 0 })
const res = await fetch(new URL('/orders', server.url), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ item: 'widget' })
})
expect(res.status).toBe(400)
const body = (await res.json()) as { issues: { message: string }[] }
expect(Array.isArray(body.issues)).toBe(true)
server.stop()
})
```
## Testing a WebSocket route [#testing-a-websocket-route]
The same `app.listen({ port: 0 })` server also serves registered [WebSocket routes](../routing/websockets.mdx). Open a `WebSocket` against `server.url` with the protocol swapped to `ws:`:
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
test('a ws route echoes messages', async () => {
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
const server = app.listen({ port: 0 })
const wsUrl = new URL('/chat', server.url)
wsUrl.protocol = 'ws:'
const ws = new WebSocket(wsUrl)
await new Promise(resolve => {
ws.addEventListener('open', () => resolve())
})
const reply = new Promise(resolve => {
ws.addEventListener('message', event => resolve(event.data as string))
})
ws.send('hi')
expect(await reply).toBe('echo: hi')
ws.close()
server.stop()
})
```
For unit-testing a piece of middleware on its own, without running a server at all, see [Testing middleware](./testing-middleware.mdx).
# Body Parsers (/en/docs/validation/body-parsers)
Body parsing only happens for a route that declared a `body` schema — see
[Body](./body.mdx). Arcton picks a parser by the request's `Content-Type`
(parameters like `; charset=` are ignored, and the match is
case-insensitive), runs it, and hands the result to your schema. A route
accepts only `application/json` by default; any other media type
has to be listed with `content` — see
[Accepting specific media types](./body.mdx#accepting-specific-media-types).
## Built-in parsers [#built-in-parsers]
These are the parsers Arcton ships. A route only ever receives a media type it
accepts: `application/json` by default, or the ones it lists in `content`.
| Content-Type | Parsed value |
| ----------------------------------------------- | ---------------------- |
| `application/json` and any `application/*+json` | `await request.json()` |
| `text/plain` | `string` |
| `application/x-www-form-urlencoded` | `FormData` |
| `multipart/form-data` | `FormData` |
| `application/octet-stream` | `ArrayBuffer` |
A request whose `Content-Type` the route doesn't accept — or that has no
parser, built-in or custom — gets `415` with an empty body. A built-in parser that
throws on malformed input (invalid JSON, for instance) responds `400` with
`{"issues":[{"message":"Invalid request body"}]}`. A request with no body at
all never reaches a parser when the route's body is
[optional](./body.mdx#optional-bodies).
## Registering your own parser [#registering-your-own-parser]
`app.parser(mediaType, parser)` registers a parser for an exact media type,
overriding a built-in for the same type if there is one. Registering the same
media type again replaces the previous parser — it's a flat table, not an
ordered pipeline, so it doesn't matter when relative to your routes you call
it.
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.parser('text/csv', async request => {
const [header = '', ...rows] = (await request.text()).trim().split('\n')
const keys = header.split(',')
return rows.map(row =>
Object.fromEntries(keys.map((key, i) => [key, row.split(',')[i]]))
)
})
app.post('/import', {
body: {
content: { 'text/csv': v.array(v.record(v.string(), v.string())) }
},
handler: ctx => ({ imported: ctx.body.length, rows: ctx.body })
})
app.listen()
```
A `BodyParser` receives the raw `Request`, not `ctx` — parsing has nothing to
do with route context.
Returning `undefined` from a custom parser means "I don't handle this
request" and falls back to `415`, the same as no parser being registered at
all. Any other value counts as handled, including `false`, `0` and `''`. A
custom parser that throws propagates uncaught, the same as a handler or
`provide()` throwing — it isn't caught into a `400` the way a built-in
parser's throw is.
# Body (/en/docs/validation/body)
Declaring a `body` schema on a route's options gives you `ctx.body` — the
request body, parsed according to its `Content-Type` and validated against
your schema:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({
name: v.pipe(v.string(), v.minLength(1)),
email: v.pipe(v.string(), v.email())
}),
handler: ctx => ({ created: ctx.body })
})
app.listen()
```
`ctx.body` only appears — and only type-checks — on a route that declared a
`body` schema this way. A route without one doesn't have `ctx.body` at all.
## Body isn't only JSON [#body-isnt-only-json]
A route accepts `application/json` and nothing else by default. Any other media
type — `text/plain`, a form body, even a `+json` subtype like
`application/vnd.api+json` — answers `415` before anything is parsed, unless the
route declares it explicitly with
[`content`](#accepting-specific-media-types). Whatever value that media type
parses to is what your schema validates against, so a route can take plain text:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/notes', {
body: { content: { 'text/plain': v.pipe(v.string(), v.minLength(1)) } },
handler: ctx => ({ length: ctx.body.length })
})
app.listen()
```
or describe a `FormData` body:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/upload', {
body: { content: { 'multipart/form-data': v.instance(FormData) } },
handler: ctx => ({ received: ctx.body.get('name') })
})
app.listen()
```
Which `Content-Type` values parse to which JavaScript value — and what happens
when the request's `Content-Type` isn't one Arcton knows how to parse — is
covered in [Body Parsers](./body-parsers.mdx).
## Optional bodies [#optional-bodies]
A `body` is required by default: a request with no body at all is rejected
before your schema runs. To also accept one, pass `{ schema, optional: true }`
instead of a bare schema:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/reviews/:id/dismiss', {
body: {
schema: v.object({ reason: v.optional(v.string()) }),
optional: true
},
handler: ctx => ({ dismissedWith: ctx.body?.reason ?? null })
})
app.listen()
```
A request that carries no body skips parsing and validation, and `ctx.body` is
`undefined` — it is not turned into `{}`, and the schema never sees it. The
type follows: `ctx.body` is the schema's output or `undefined`. A request that
does carry a body is handled exactly as before: `{}` goes through the schema,
malformed JSON is still a `400`, an unsupported `Content-Type` still a `415`.
"No body" means the request carries none — a `Content-Type` header on its own
doesn't make one.
## Accepting specific media types [#accepting-specific-media-types]
A bare `schema` accepts only `application/json`. To accept other media types, or
several, each with its own schema, use `content` instead of `schema`. `content`
replaces that default, so list `application/json` too if the route should keep
taking it:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/webhook', {
body: {
content: {
'application/json': v.object({ event: v.string() }),
'text/plain': v.pipe(v.string(), v.minLength(1))
}
},
handler: ctx => ({ via: ctx.contentType, received: ctx.body })
})
app.listen()
```
A request whose `Content-Type` isn't listed responds `415` before anything is
parsed. Matching ignores case and parameters like `; charset=`, and is exact
otherwise: `application/vnd.api+json` doesn't match `application/json`. The
matched media type is `ctx.contentType`, and `ctx.body` is the output of that
media type's schema — so its type is the union of the outputs. Narrowing
`ctx.body` from `ctx.contentType` isn't type-checked yet.
`content` only decides which media types the route accepts; it doesn't teach
Arcton to read new ones. A media type with no built-in parser, like
`text/csv`, still needs an
[`app.parser()`](./body-parsers.mdx#registering-your-own-parser) — without one
it answers `415`; registering one never changes what a bare `schema` accepts.
`optional: true` works the same way as with `schema`: a
request with no body leaves both `ctx.body` and `ctx.contentType` `undefined`.
Use either `schema` or `content`, never both. [OpenAPI](../integrations/openapi.mdx)
documents each listed media type with its schema.
## Order [#order]
`body` validates last, after `params` and `query` — see
[Validation Overview](./overview.mdx). A failing body schema responds with
`400` the same way params or query failures do — see
[Validation Errors](./validation-errors.mdx).
# Validation Overview (/en/docs/validation/overview)
Any HTTP method also accepts an options object instead of a plain handler,
letting you attach a schema to `params`, `query` and/or `body`:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
query: v.object({
notify: v.optional(
v.pipe(
v.string(),
v.transform(s => s === 'true'),
v.boolean()
)
)
}),
body: v.object({
item: v.pipe(v.string(), v.minLength(1)),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
handler: ctx => ({
userId: ctx.params.id,
notify: ctx.query.notify ?? false,
order: ctx.body
})
})
app.listen()
```
`ctx.params.id` is a `number` here, not a `string` — validation replaces
`ctx.params`, `ctx.query` and `ctx.body` with the schema's output, so
coercions and transforms are what the handler actually sees.
## Any Standard Schema works [#any-standard-schema-works]
`params`, `query` and `body` each accept any
[Standard Schema](https://standardschema.dev/) — Zod 3.24+, Valibot and
ArkType all implement it, so any of them work here. The examples across this
section use Valibot; stay consistent within whichever schema library you pick
for a project.
## Order and short-circuiting [#order-and-short-circuiting]
Validation runs **params → query → body**, in that order. The first schema
that fails responds immediately with `400` and nothing downstream — route
middleware, the handler — runs. See
[Validation Errors](./validation-errors.mdx) for the exact response shape.
Body validation only runs for a route that declared a `body` schema, and only
after the request body has been parsed according to its `Content-Type` — see
[Body Parsers](./body-parsers.mdx). Global middleware runs before any of this,
so it always sees the raw, un-coerced `ctx.params` / `ctx.query` — see
[Execution Order](../middleware/execution-order.mdx).
For the deeper look at each piece, see
[Params and Query](./params-and-query.mdx) and [Body](./body.mdx).
# Params and Query (/en/docs/validation/params-and-query)
Without a schema, `ctx.params` comes from the route literal and `ctx.query` is
`Record` — see [Context](../fundamentals/context.mdx),
[Path Parameters](../routing/path-parameters.mdx) and
[Query Parameters](../routing/query-parameters.mdx). Declaring a `params` or
`query` schema replaces either with the schema's own output, coercions
included.
## Params [#params]
Route params always arrive as strings — a `params` schema is how you turn
`:id` into something more useful:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/users/:id', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
handler: ctx => ({ id: ctx.params.id, doubled: ctx.params.id * 2 })
})
app.listen()
```
`ctx.params.id` is typed and valued as a `number`, so arithmetic on it just
works.
## Query [#query]
Query values are strings too, and often optional — a query schema is where
you turn `?limit=10` into a real number with a real default:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/search', {
query: v.object({
q: v.pipe(v.string(), v.minLength(1)),
limit: v.optional(
v.pipe(v.string(), v.transform(Number), v.number())
)
}),
handler: ctx => ({ query: ctx.query.q, limit: ctx.query.limit ?? 10 })
})
app.listen()
```
`limit` stays `number | undefined` since it's optional — the fallback with
`??` happens in the handler.
## Order [#order]
When a route declares both, `params` validates before `query`, and either can
short-circuit the request with `400` before the other runs — see
[Validation Overview](./overview.mdx) and
[Validation Errors](./validation-errors.mdx).
# Validation Errors (/en/docs/validation/validation-errors)
When a `params`, `query` or `body` schema fails, Arcton responds `400` with an
`application/json` body carrying the issues the schema reported:
```json
{
"issues": [
{ "message": "Invalid length: Expected >=1 but received 0", "path": ["..."] }
]
}
```
The `issues` array is exactly what your schema library returned from its own
validation call — Arcton doesn't reshape or filter it. Every issue has a
`message`, and each library adds its own fields alongside it.
Valibot, for example, returns issues carrying `kind`, `type`, `input`,
`expected`, `received` and `requirement`, with a `path` of segment objects
rather than plain keys:
```json
{
"issues": [
{
"kind": "validation",
"type": "min_length",
"input": "",
"expected": ">=1",
"received": "0",
"message": "Invalid length: Expected >=1 but received 0",
"requirement": 1,
"path": [{ "type": "object", "origin": "value", "key": "item" }]
}
]
}
```
Zod and ArkType report their own shapes. Read `message` when you need something
stable across libraries, and treat the rest as specific to the one you chose —
if a client depends on the exact fields, pin the schema library that produces
them.
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({
email: v.pipe(v.string(), v.email())
}),
handler: ctx => ({ created: ctx.body })
})
app.listen()
```
A `POST /users` with a body whose `email` field fails `v.email()` gets the
`400` above; a request whose `email` passes reaches the handler with
`ctx.body.email` already validated.
## Handling validation failures yourself [#handling-validation-failures-yourself]
That `400` is the default. A validation failure is an ordinary error, so it
reaches [`app.onError()`](../errors/global-error-handler.mdx#validation-errors-go-through-it-too)
as a `ValidationError` carrying the same `issues`: return a value or a
`Response` there to replace the response, or return nothing to keep this one.
## What short-circuits and what doesn't [#what-short-circuits-and-what-doesnt]
Validation runs **params → query → body**, and the first failing schema stops
the request right there — nothing after it in that order runs, and neither
does any route middleware or the handler. See
[Validation Overview](./overview.mdx).
Two related failures happen outside schema validation itself, before your
schema ever sees a value:
* An unsupported request `Content-Type` for a route with a `body` schema
responds `415`, before any parsing or validation is attempted.
* A built-in parser that can't make sense of the body at all (malformed JSON,
for instance) responds `400` with a fixed
`{"issues":[{"message":"Invalid request body"}]}` — this message isn't from
your schema, since the schema never got a value to validate.
Both are covered in full in [Body Parsers](./body-parsers.mdx).
# Arcton (/es/docs)
Arcton es un framework backend para TypeScript. Escribes handlers que
retornan valores, compones comportamiento con middleware, y organizas una
aplicación en módulos que se fusionan en un único árbol de rutas.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ message: 'Welcome to Arcton' }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen({ port: 3000 })
```
`ctx.params.id` está tipado como `string` porque el literal de la ruta lo
dice — sin argumento genérico, sin cast. El objeto retornado se convierte en
una respuesta JSON.
## Empieza aquí [#empieza-aquí]
Una línea recta de cero a un servidor corriendo:
## Conceptos centrales [#conceptos-centrales]
Las ideas que aparecen en todo lo demás de Arcton:
## Correr una app de verdad [#correr-una-app-de-verdad]
## Referencia [#referencia]
Arcton está en pre-1.0. La API descrita aquí es la que se envía hoy.
# Adapters (/es/docs/architecture/adapters)
Un adapter es la única parte de Arcton que habla con un runtime. Recibe
una función estilo `fetch` y una lista de rutas WebSocket, arranca un
servidor real, y retorna un handle.
```ts
import type { RuntimeServeOptions, RuntimeServer } from '@arcton/contracts'
interface RuntimeAdapter {
readonly name: string
readonly version: string
readonly capabilities: { readonly websocket: boolean }
serve(options: RuntimeServeOptions): RuntimeServer
}
```
Esa es toda la superficie entre Arcton y el mundo.
## Por qué existe este límite [#por-qué-existe-este-límite]
Bun y Node.js discrepan en casi todo a nivel de servidor: cómo arranca
un servidor, cómo se representa un request, cómo se escribe una
respuesta, cómo se expresa un upgrade de socket. Coinciden en `Request`
y `Response`.
Construir el límite justo en ese acuerdo mantiene el routing, el
pipeline y el mapeo de respuestas independientes del runtime — lo cual
significa que se escriben una vez, se testean una vez, y se comportan
idéntico donde sea que corra la app. El trabajo por runtime se reduce
a traducción, y cada adapter es un solo archivo.
También significa que agregar un runtime no toca el core. Cualquier
cosa que pueda aceptar un `Request` y producir un `Response` puede
respaldar un adapter.
## De qué es responsable un adapter [#de-qué-es-responsable-un-adapter]
* Arrancar un servidor en un puerto y hostname, y reportar el `port` y
la `url` reales — incluyendo el puerto real cuando se pidió `0`.
* Convertir el request nativo del runtime en un `Request` estándar, y
escribir de vuelta un `Response` estándar, headers y body en stream
incluidos.
* Hacer el upgrade de las rutas WebSocket que se le entregaron, y
traducir el socket del runtime a la interfaz de socket compartida.
* Detenerse, con la opción de cerrar las conexiones activas.
* Capturar cualquier cosa que se tire fuera del handler del request,
loguearla, y responder `500` — la última línea de defensa, para que
un runtime nunca vea un rejection sin manejar del código del usuario.
## De qué no es responsable un adapter [#de-qué-no-es-responsable-un-adapter]
Un adapter no hace ningún routing. Cada request va directo al handler
que le dio Arcton, sea cual sea el path — los propios tests de los
adapters verifican exactamente eso. No sabe nada de middleware,
providers, validation ni módulos, y nunca inspecciona el body de un
request o de una respuesta.
Mantener a los adapters así de delgados es lo que los hace
intercambiables. Si un adapter empezara a tomar decisiones de routing,
dos runtimes podrían responder el mismo request de manera distinta, y
la promesa de que una app se comporta igual en todos lados dejaría de
ser cierta silenciosamente.
## Capabilities [#capabilities]
Algunas funcionalidades de runtime no se pueden emular. `capabilities`
las describe, y hoy lleva una sola bandera, `websocket`.
Arcton la verifica en `listen()` en vez de en `ws()`, porque un módulo
montado después de una llamada a `ws()` todavía puede aportar rutas
WebSocket — `listen()` es el primer momento en que se conoce el
conjunto final. Verificar al arrancar significa que un desajuste falla
de inmediato con un mensaje que nombra el runtime, en vez de en el
primer intento de upgrade.
## Diferencias que siguen siendo visibles [#diferencias-que-siguen-siendo-visibles]
La abstracción cubre comportamiento, no cada detalle de la plataforma
subyacente. Dos diferencias llegan hasta el usuario:
* `stop()` se completa de forma síncrona en Bun y retorna una promesa
en Node.js, porque el `close()` de Node es inherentemente asíncrono.
Awaitearlo funciona en ambos.
* `version` reporta la propia versión del runtime, así que su formato
sigue al runtime.
Ambas están documentadas en
[Runtime support](../introduction/runtime-support.mdx), porque fingir
que son idénticas sería un trade peor que nombrarlas.
## Escribir un adapter [#escribir-un-adapter]
Implementa `RuntimeAdapter` y pásale la instancia a `listen()`:
```ts
import type { RuntimeAdapter } from '@arcton/contracts'
export const myAdapter: RuntimeAdapter = {
name: 'my-runtime',
version: '1.0.0',
capabilities: { websocket: false },
serve(options) {
// start a server that calls options.fetch(request, context)
// and writes the returned Response back
return {
port: options.port,
url: new URL(`http://localhost:${options.port}/`),
stop() {}
}
}
}
```
La implementación de `serve()` tiene que llamar a `options.fetch` en
cada request y escribir de vuelta el `Response` que sea que retorne.
Ver [Runtime types](../api/runtime-types.mdx) para el contrato
completo.
# Design Decisions (/es/docs/architecture/design-decisions)
Cada entrada aquí es una decisión que razonablemente podría haber ido
de otra manera. Esta página dice qué se eligió y por qué; la página
enlazada tiene el detalle.
## El orden de registro decide el pipeline de una ruta [#el-orden-de-registro-decide-el-pipeline-de-una-ruta]
Una ruta corre el middleware y los providers registrados antes que
ella, capturados como un snapshot cuando se crea la ruta.
La alternativa — aplicar cada `use()` a cada ruta sin importar la
posición — era el comportamiento original, y se volvió inconsistente
apenas `provide()` introdujo contexto tipado, porque el tipo de `ctx`
depende necesariamente de lo que vino antes. En vez de mantener dos
reglas de orden distintas, una para los tipos y otra para el runtime,
ambas se convirtieron en la misma regla.
→ [Execution order](../middleware/execution-order.mdx)
## El middleware global sigue corriendo en 404 y 405 [#el-middleware-global-sigue-corriendo-en-404-y-405]
La regla del snapshot es relativa a una ruta, y esas respuestas no
tienen ninguna ruta. Como las cosas que viven en el middleware global
— CORS, logging, request ids — solo son correctas si cubren cada
respuesta, el middleware sin scope aplica ahí sin importar dónde se
registró.
→ [Global middleware](../middleware/global.mdx)
## El path más específico es dueño de la URL, para cada método [#el-path-más-específico-es-dueño-de-la-url-para-cada-método]
Cuando el matching llega a un nodo con handlers pero ninguno para el
método del request, responde `405` en vez de seguir buscando otro
patrón que lo aceptara. De lo contrario, una misma URL podría resolver
a rutas distintas según el verbo.
→ [Precedence](../routing/precedence.mdx)
## Las rutas viven en un árbol con tres slots fijos [#las-rutas-viven-en-un-árbol-con-tres-slots-fijos]
Hijos static en un map, un slot dynamic, un slot wildcard. La
prioridad está codificada en la estructura en vez de en un
ordenamiento, las búsquedas no escalan con la cantidad de rutas, y el
resultado nunca depende del orden de registro.
→ [Router](./router.mdx)
## Montar fusiona árboles al registrarse [#montar-fusiona-árboles-al-registrarse]
Un router anidado cuesta una pasada de matching por nivel en cada
request. Fusionar cuesta un solo injerto al arrancar y nada después, y
hace que los conflictos salgan a la luz de inmediato.
→ [Module composition](./module-composition.mdx)
## Un módulo es una aplicación [#un-módulo-es-una-aplicación]
En vez de un tipo `Router` separado, un módulo es una instancia de
`Arcton()` con un prefix. Una sola API que aprender, y un módulo se
puede correr de forma independiente durante el desarrollo.
→ [Modules](../routing/modules.mdx)
## Middleware, providers y validation comparten una secuencia [#middleware-providers-y-validation-comparten-una-secuencia]
Una sola lista ordenada en vez de fases por cada cosa, así que el
orden en que escribes algo es el orden en que corre, y no hay ninguna
tabla de precedencia entre tipos de step.
→ [Pipeline](./pipeline.mdx)
## Los providers no tienen `next` [#los-providers-no-tienen-next]
Un provider calcula un valor y continúa. Decidir si el resto de la
cadena corre es trabajo de un middleware, y mantener las dos cosas
separadas hace que un provider no pueda convertirse accidentalmente en
control de flujo.
→ [Providers vs middleware](../providers/providers-vs-middleware.mdx)
## Los valores provistos quedan planos sobre el context [#los-valores-provistos-quedan-planos-sobre-el-context]
Los valores de un provider caen directamente sobre el context, así que
un handler lee `ctx.user`. Agruparlos bajo un namespace agregaría un
nivel de anidamiento a cada acceso a cambio de evitar colisiones — y
las colisiones ya se previenen en tiempo de compilación, ya que
volver a proveer una key existente o uno de los campos base del
context no pasa el chequeo de tipos.
→ [Typed context](../providers/typed-context.mdx)
## Los handlers retornan valores [#los-handlers-retornan-valores]
Un valor retornado se mapea a un `Response`, así que un handler se
mantiene como una función ordinaria que retorna datos: fácil de
testear, imposible de enviar dos veces. Retornar un `Response` sigue
disponible para tener control total.
→ [Response](../fundamentals/response.mdx)
## `ctx.response` es mutable hasta que el body se finaliza [#ctxresponse-es-mutable-hasta-que-el-body-se-finaliza]
El middleware necesita asignar headers después de que el handler ya
corrió, y un `Response` real no se puede mutar de esa forma. El
pipeline mantiene un objeto mutable de staging y lo materializa apenas
un body existe en cualquier capa, que es lo que hace que los cambios
de headers post-`next()` se mantengan.
El costo aceptado es que el status queda fijo desde ese punto en
adelante, ya que un `Response` real lo expone como solo lectura.
→ [Modifying responses](../middleware/modifying-responses.mdx)
## Un `Response` crudo gana sin condiciones [#un-response-crudo-gana-sin-condiciones]
Cuando un handler o un middleware retorna un `Response`, se usa tal
cual — sin fusionar los headers o el status acumulados. Fusionar
haría que el resultado dependiera de capas que el autor de ese
`Response` no puede ver; pasarlo directo mantiene predecible la
válvula de escape.
→ [Response](../fundamentals/response.mdx)
## La validation habla Standard Schema [#la-validation-habla-standard-schema]
Aceptar cualquier librería que implemente
[Standard Schema](https://standardschema.dev/) significa que Arcton
nunca depende de un validador ni impone uno, mientras que el tipo de
salida del schema igual fluye hacia el handler.
→ [Validación](../validation/overview.mdx)
## El body parsing está separado de la validation [#el-body-parsing-está-separado-de-la-validation]
Un schema valida un valor que ya está en memoria y no sabe nada de
HTTP. Convertir bytes en ese valor, según el `Content-Type`, es una
cosa separada con su propio punto de extensión en `app.parser()`.
→ [Body parsers](../validation/body-parsers.mdx)
## Los parsers son una tabla plana, no steps del pipeline [#los-parsers-son-una-tabla-plana-no-steps-del-pipeline]
`app.parser()` mapea un media type a un parser. Registrar el mismo
tipo de nuevo lo reemplaza. Los parsers no tienen semántica de orden
ni de snapshot porque no hay ninguna composición que expresar:
exactamente un parser maneja un `Content-Type` dado.
→ [Body parsers](../validation/body-parsers.mdx)
## Los scopes de path deben ser static [#los-scopes-de-path-deben-ser-static]
Un scope se compara contra el path de una ruta como una relación
simple entre dos paths. Permitir segmentos `:param` convertiría al
matching de scopes en un segundo sistema de pattern-matching corriendo
al lado del router.
→ [Scoped middleware](../middleware/scoped.mdx)
## Los prefixes también deben ser static [#los-prefixes-también-deben-ser-static]
Un prefix dinámico haría que los parámetros de un módulo dependieran
de dónde se lo montó, rompiendo la inferencia de `ctx.params` a partir
del literal de la ruta.
→ [Modules](../routing/modules.mdx)
## El soporte de runtime es una interfaz, no un target de build [#el-soporte-de-runtime-es-una-interfaz-no-un-target-de-build]
`RuntimeAdapter` es una interfaz pública en un paquete solo-tipos, así
que el core se escribe una vez y cada runtime es una capa de
traducción delgada elegida en `listen()`.
→ [Adapters](./adapters.mdx)
## Las capabilities se verifican en `listen()` [#las-capabilities-se-verifican-en-listen]
Un módulo montado después de una llamada a `ws()` todavía puede
agregar rutas WebSocket, así que `listen()` es el primer punto donde
se conoce el conjunto final — y arrancar es donde un desajuste
debería salir a la luz.
→ [WebSockets](../routing/websockets.mdx)
## Los conflictos tiran un error al registrarse [#los-conflictos-tiran-un-error-al-registrarse]
Rutas duplicadas, nombres de parámetro en conflicto, paths inválidos,
scopes y prefixes no static, todos tiran un error al registrarse.
Arrancar es el lugar más barato posible para encontrarlos, y el
mensaje puede nombrar la ruta.
→ [Registration errors](../errors/registration-errors.mdx)
## El trabajo pasa al registrarse, no por request [#el-trabajo-pasa-al-registrarse-no-por-request]
El hilo conductor de casi todo lo anterior. Un request matchea un
path, corre una cadena ya preparada, y mapea un valor — todo lo demás
ya se decidió cuando se construyó la aplicación.
→ [Overview](./overview.mdx)
# Module Composition (/es/docs/architecture/module-composition)
`app.use(module)` toma el árbol de rutas del módulo y lo injerta en el
árbol del padre, justo en esa llamada. Después hay un solo árbol, y
nada registra que un módulo alguna vez estuvo involucrado.
## La alternativa que Arcton no tomó [#la-alternativa-que-arcton-no-tomó]
El enfoque común es un router anidado: el padre guarda una referencia
al hijo y, cuando llega un request con un prefix que coincide, se lo
delega. Eso es simple de implementar y cuesta algo en cada request —
un match en el padre, después un match en el hijo, y otra vez por cada
nivel de anidamiento. Una estructura de tres niveles significa tres
pasadas de matching por request, para siempre.
Fusionar paga ese costo una sola vez, al arrancar. Un request contra
un módulo anidado profundamente cuesta exactamente lo mismo que una
ruta de nivel superior, porque para cuando llegan los requests ya no
queda ningún anidamiento — solo un árbol.
## Qué hace la fusión en realidad [#qué-hace-la-fusión-en-realidad]
El injerto recorre el árbol del módulo e inserta cada ruta en el árbol
del padre bajo el prefix combinado, usando las mismas primitivas de
get-or-create y de conflicto que usa un `app.get()` directo. De
reusar esas primitivas en vez de duplicarlas se siguen dos cosas:
* Una colisión producida al montar tira el mismo error, con el mismo
mensaje, que registrar una ruta duplicada a mano. No hay una segunda
clase de conflicto que aprender.
* Un conflicto de nombre de parámetro entre una ruta montada y una
existente se captura de la misma forma, en el mismo momento.
El propio árbol del módulo queda intacto, así que el mismo módulo se
puede montar en más de un padre.
## Envolver, una sola vez [#envolver-una-sola-vez]
Cada handler montado se envuelve con los steps globales del padre tal
como existían en el momento del montaje — la misma regla de snapshot
que gobierna a una ruta registrada directamente.
El envoltorio pasa una sola vez por handler, en tiempo de montaje, no
por request. Un handler que llegó a través de dos niveles de montaje
tiene el middleware de ambos padres incorporado en él, en el orden
correcto, sin ninguna composición en tiempo de request.
El middleware con scope del padre queda excluido a propósito. Un
scope es una afirmación sobre el propio path de una ruta, y un módulo
llega como un subárbol entero sin un único path contra el cual
comparar — así que no hay nada sólido contra qué compararlo. En vez de
adivinar, montar descarta los steps con scope, y el módulo conserva su
propio middleware con scope, que se compara contra los paths locales
del módulo. El mismo razonamiento gobierna qué corre en
[404 y 405](../middleware/execution-order.mdx).
## Por qué un módulo es simplemente una aplicación [#por-qué-un-módulo-es-simplemente-una-aplicación]
No hay ningún tipo `Router` que aprender. Un módulo es una instancia
de `Arcton()`, lo que significa que tiene la API completa: su propio
middleware, sus propios providers, su propia validation, sus propios
módulos.
Eso tiene una ganancia práctica. Un módulo se puede desarrollar y
correr por su cuenta — llamar a `listen()` sobre él directamente
durante el desarrollo, montarlo en el padre en producción — porque
nunca hubo nada distinto en él.
## Qué te cuesta la fusión [#qué-te-cuesta-la-fusión]
Fusionar al registrarse significa que el árbol se construye a partir
de lo que existe en ese momento, lo que produce una regla que vale la
pena recordar: las rutas agregadas a un módulo *después* de haber sido
montado no aparecen en el padre. Monta un módulo una vez que ya está
completamente construido.
A cambio, la forma de la aplicación queda fija una vez que se llama a
`listen()`. Nada del routing puede cambiar entre requests, es
imposible introducir conflictos en runtime, y la tabla de rutas se
conoce desde que arranca.
## Prefixes [#prefixes]
Un prefix se guarda en la instancia y se aplica cuando se registra una
ruta sobre ella — así que las rutas de un módulo ya tienen prefix para
cuando algo lo monta, y montar simplemente agrega encima el prefix del
padre.
Los prefixes deben ser paths static. Un prefix dinámico haría que los
parámetros de las rutas montadas dependieran de dónde se montaron, y
`ctx.params` dejaría de poder derivarse del literal de la ruta que
escribió el módulo. Mantener los prefixes static conserva intacta esa
inferencia en cada nivel de anidamiento.
# Architecture Overview (/es/docs/architecture/overview)
Arcton está construido a partir de cuatro piezas con responsabilidades
acotadas:
| Capa | Es dueña de | No sabe nada de |
| ---------------- | ------------------------------------------------ | -------------------- |
| Adapter | arrancar un servidor, request nativo ↔ `Request` | routing, middleware |
| Router | mapear un método y un path a un handler | qué hace un handler |
| Pipeline | correr middleware, providers y validation | cómo matcheó un path |
| Response mapping | convertir un valor retornado en un `Response` | el resto del request |
Las páginas de esta sección explican por qué cada una está construida
como está. Si buscas cómo usarlas, empieza por
[Fundamentos](../fundamentals/application.mdx) en su lugar.
## Una decisión le da forma a la mayoría del resto [#una-decisión-le-da-forma-a-la-mayoría-del-resto]
Arcton resuelve todo lo que puede **cuando las rutas se registran**, no
cuando llegan los requests.
* Una ruta guarda su propia cadena de middleware ya terminada, capturada
al registrarse.
* Montar un módulo fusiona su árbol de rutas en el del padre, una sola
vez.
* Los scopes de path se resuelven en cadenas por ruta, así que el
router nunca se entera de que los scopes existen.
* Los conflictos entre rutas se detectan al registrarse y tiran un
error de inmediato.
En tiempo de request, lo que queda es: matchear un path, correr una
cadena ya preparada, mapear un valor. Nada tiene que recalcularse, y
nada de la forma de la aplicación puede cambiar entre requests.
Esto también mantiene honesto al sistema de tipos. `ctx` se tipa a
partir de los providers registrados antes de un handler, y ese es
exactamente el conjunto que corre — porque los tipos y el runtime leen
la misma lista, en el mismo orden. Ver [Pipeline](./pipeline.mdx).
## Dónde están los límites [#dónde-están-los-límites]
```text
@arcton/adapter-bun @arcton/adapter-node
└───────────┬───────────────┘
│ implementa RuntimeAdapter
@arcton/contracts ← el vocabulario compartido
│ solo tipos, sin código de runtime
@arcton/core ← routing, pipeline, mapeo
│
tu aplicación
```
`@arcton/contracts` no tiene ninguna lógica. Existe para que el core y
los adapters puedan depender de una descripción compartida de un
runtime sin depender entre sí, y para que tu propio código pueda
nombrar esos tipos. Ver
[Runtime abstraction](./runtime-abstraction.mdx).
## Orden de lectura [#orden-de-lectura]
# Pipeline (/es/docs/architecture/pipeline)
Todo lo que pasa entre matchear una ruta y llamar a su handler es una
sola lista de steps. Hay tres tipos:
| Step | Comportamiento |
| ---------- | ------------------------------------------------------------------------------- |
| middleware | onion completo: recibe `next`, puede cortar la cadena, corre código a la salida |
| provider | fusiona su resultado en el context y continúa, sin `next` propio |
| validation | valida params, query y body, reemplazándolos con la salida validada |
Viven en una única secuencia en orden de registro, y el pipeline la
recorre en ese orden.
## Por qué una sola secuencia [#por-qué-una-sola-secuencia]
La alternativa es una fase por cada cosa: correr todos los providers,
después todas las validations, después todo el middleware. Eso se ve
bien en un diagrama y está mal en la práctica, porque un provider
seguido depende de algo que hizo un middleware, o de algo que hizo
otro provider.
Mantener una sola lista significa que el orden en que escribiste algo
es el orden en que corre. También significa que hay exactamente una
regla que aprender en vez de una tabla de precedencia entre distintas
cosas.
Los tres tipos de step igual difieren donde tienen que hacerlo: un
provider no tiene `next` porque "correr el resto de la cadena" no es
una decisión que le corresponda tomar — esa distinción es toda la
diferencia entre [providers y middleware](../providers/providers-vs-middleware.mdx).
## Por qué la secuencia se saca como snapshot por ruta [#por-qué-la-secuencia-se-saca-como-snapshot-por-ruta]
Cuando se registra una ruta, la lista actual de steps se copia y se
guarda junto con esa ruta. Los requests nunca leen una lista
compartida y mutable.
Esto es lo que hace que el orden de registro tenga sentido: una ruta
corre los steps que existían cuando se creó, y nada registrado después
puede alcanzarla. La alternativa — leer una lista en vivo en tiempo de
request — significaría que una llamada a `use()` al final de un
archivo cambiaría silenciosamente rutas del principio, y rompería la
correspondencia con el sistema de tipos.
Esa correspondencia es la ganancia real. `ctx` se tipa a partir de los
providers registrados antes del handler, y esos son exactamente los
providers que corren, porque la acumulación a nivel de tipos y el
array en runtime son la misma secuencia leída de la misma manera. No
hay ninguna aproximación conservadora de ningún lado.
De este snapshot se siguen dos consecuencias:
* Los scopes de path se resuelven aquí, no en el router. Cuando se
registra una ruta, se conserva el middleware con scope bajo cuyo
path está esa ruta, y se descarta el resto. El matcher nunca se
entera de que los scopes existen — ver [Router](./router.mdx).
* Una ruta sin ningún step directamente se salta el pipeline y llama
al handler, así que una ruta simple no cuesta más que la función que
envuelve.
## Dónde se ubica la validation [#dónde-se-ubica-la-validation]
La validation se inserta después de los steps globales y antes del
middleware de ruta. Esa posición es deliberada:
* El middleware global corre primero, así que las cosas transversales
como CORS y logging aplican incluso a requests que fallan la
validation.
* El middleware de ruta corre después, así que ve los valores ya
validados y convertidos — un middleware de ruta que lee `ctx.body`
recibe el body ya parseado y tipado, no uno crudo.
Un schema que falla corta la cadena por el mismo mecanismo que usa un
middleware cuando retorna sin llamar a `next()`. Hay un solo camino de
corte de cadena, no un caso especial para la validation.
## Materializar la respuesta [#materializar-la-respuesta]
`ctx.response` empieza como un objeto simple que guarda un status y
headers. En el momento en que un body se finaliza en cualquier capa,
Arcton lo mapea a un `Response` real y lo guarda de vuelta en
`ctx.response`.
Materializar en cada capa, en vez de una sola vez al final, es lo que
le permite a un middleware mutar headers después de `await next()` y
que el cambio sobreviva — incluso cuando una capa interior retornó un
`Response` crudo, que de otro modo hubiera descartado todo lo
acumulado a su alrededor.
El trade-off es visible en la API: un `Response` real expone headers
mutables pero un status de solo lectura, así que un status solo puede
asignarse antes de que el body se finalice. Esa es una restricción
real que el diseño acepta en vez de esconder — ver
[Modifying responses](../middleware/modifying-responses.mdx).
## 404 y 405 [#404-y-405]
Esas respuestas no tienen ninguna ruta matcheada, así que no hay
ningún snapshot por ruta que usar. Arcton junta el middleware global
sin scope una sola vez, cuando se llama a `listen()`, y corre la misma
maquinaria del pipeline contra un handler de fallback.
El middleware con scope, el middleware de ruta y los providers quedan
excluidos porque cada uno de ellos pertenece a una ruta que, por
definición, no matcheó. El middleware global sí se incluye porque las
cosas que viven ahí — CORS, logging, request ids — tienen que cubrir
cada respuesta HTTP para ser correctas en absoluto. Ver
[Execution order](../middleware/execution-order.mdx).
## Qué cuesta el pipeline [#qué-cuesta-el-pipeline]
Por request, en una ruta con steps: un recorrido de un array ya
preparado, un objeto de context, y un mapeo del valor retornado. Por
request en una ruta sin steps: la llamada al handler y el mapeo.
El trabajo que no está ahí es justamente el punto. Ninguna búsqueda de
qué middleware aplica, ningún matching de scopes, ninguna composición
de la cadena por request — todo eso ya pasó una sola vez, al
registrarse.
# Router Internals (/es/docs/architecture/router)
El router responde una sola pregunta: dado un método y un pathname,
¿qué handler corre y cuáles son sus parámetros?
## Por qué un árbol [#por-qué-un-árbol]
La implementación obvia es una lista de patrones probados en orden. Es
simple, pero el costo de un request crece con la cantidad de rutas, y
la respuesta depende del orden de registro — lo que significa que
agregar una ruta puede cambiar silenciosamente qué handler alcanza un
request existente.
Arcton guarda las rutas en un árbol en su lugar, un nodo por segmento
de path. El matching recorre los segmentos del request y desciende. El
costo sigue la *profundidad* del path, no la *cantidad* de rutas, y la
forma del árbol es la misma sin importar en qué orden se registraron
las rutas.
## Tres slots por nodo [#tres-slots-por-nodo]
Cada nodo tiene exactamente tres cosas por las que se puede alcanzar
un hijo:
```text
node
├── static: Map "users" → node
├── dynamic: { name, node } ":id"
└── wildcard: { name, node } "*path"
```
Un `Map` para los hijos static hace que el caso común sea una búsqueda
por hash en vez de un escaneo. Los slots dynamic y wildcard son
únicos porque un nodo solo puede tener uno de cada uno: dos rutas que
usan nombres de parámetro distintos en la misma posición harían que
`ctx.params` fuera ambiguo, así que ese conflicto se rechaza al
registrarse en vez de resolverse arbitrariamente en tiempo de
matching.
Tener los tres tipos como slots separados también significa que la
prioridad no necesita ningún paso de ordenamiento. Static, después
dynamic, después wildcard es simplemente el orden en que están
escritas las tres verificaciones — la estructura de datos codifica la
regla de precedencia.
## Matching y backtracking [#matching-y-backtracking]
El matching desciende de forma greedy y retrocede cuando una rama
falla:
```text
1. ¿hay un hijo static con ese texto exacto? → desciende; si falla, continúa
2. ¿hay un slot dynamic? → captura, desciende; si falla,
descarta la captura y continúa
3. ¿hay un slot wildcard? → captura el resto, decide aquí
si no → falla, deja que retroceda quien llamó
```
El backtracking importa porque una rama más específica puede matchear
durante varios segmentos y después llegar a un callejón sin salida.
Dado `/a/:b/c` y `/a/*rest`, el request `/a/x/y` sigue `:b`, falla en
`c`, retrocede, y termina en el wildcard. Los parámetros capturados en
el path abandonado se eliminan al retroceder, así que un handler nunca
ve un parámetro de una rama que no matcheó.
## Por qué un método que no coincide no hace backtracking [#por-qué-un-método-que-no-coincide-no-hace-backtracking]
Cuando el matching llega a un nodo que tiene handlers pero ninguno
para este método, se detiene y reporta `405` con los métodos de ese
nodo. No sigue buscando otro patrón que aceptara el método.
La alternativa — seguir buscando hasta que algún patrón acepte el
método — significaría que `POST /users/me` podría ser servido por
`/users/:id` mientras que `GET /users/me` es servido por `/users/me`.
Un mismo path resolvería a rutas distintas según el verbo, lo cual es
más difícil de razonar que un `405`. La regla que eligió Arcton es que
el path matcheado más específico es dueño de la URL, para cada método.
[Precedence](../routing/precedence.mdx) muestra cómo se ve eso desde
afuera.
## Normalización y decodificación [#normalización-y-decodificación]
Los segmentos vacíos se descartan antes de matchear, así que
`/users`, `/users/` y `/users//` son el mismo path. Eso elimina la
configuración de slash final como concepto.
Solo los valores de parámetro capturados se decodean con
percent-decoding, y solo después de que el path ya matcheó. Decodear
primero le permitiría a un `%2F` codificado inventar un límite de
segmento que el cliente nunca envió. Un valor cuya secuencia de escape
es inválida se pasa crudo en vez de fallar el request, ya que un
escape inválido en un parámetro no es motivo para rechazar una ruta
que por lo demás matcheó.
## Validation al registrarse [#validation-al-registrarse]
Los paths de las rutas se parsean y verifican cuando se registran: el
slash inicial, la ausencia de `//`, el nombrado de parámetros, que un
wildcard sea el último, nombres de parámetro duplicados, segmentos
static que sobreviven un round trip por `URL`, y pares de método y
path duplicados.
Hacer esto al registrarse hace que el proceso falle al arrancar con un
mensaje que nombra la ruta, en vez de servir una ruta que nunca puede
matchear. Ver [Registration errors](../errors/registration-errors.mdx).
## Lo que el router no sabe [#lo-que-el-router-no-sabe]
El router guarda un handler por método por nodo, y nada más. Nunca
escuchó hablar de middleware, scopes, providers o validation: para
cuando un handler llega al árbol, toda su cadena ya está incorporada
en él. Eso es lo que mantiene el matching como un recorrido y una
búsqueda, y es por qué un scope puede existir como un concepto de
tiempo de registro sin que el matcher gane un segundo lenguaje de
patrones. Ver [Pipeline](./pipeline.mdx).
# Runtime Abstraction (/es/docs/architecture/runtime-abstraction)
`@arcton/contracts` contiene tipos y nada más. Ninguna función, ninguna
clase, ningún código de runtime. Cada otro paquete depende de él, y él
no depende de nada.
```text
@arcton/core ──┐
├──→ @arcton/contracts
@arcton/adapter-bun ──┤
@arcton/adapter-node ─┤
@arcton/cors ─────────┘
```
## Por qué un paquete separado [#por-qué-un-paquete-separado]
El core necesita describir qué espera de un runtime. Un adapter
necesita implementar exactamente eso. Si cualquiera de los dos lados
fuera dueño de la descripción, el otro tendría que depender de él — y
un adapter dependiendo del core, o el core dependiendo de cada
adapter, es un ciclo esperando a formarse.
Poner el vocabulario en un paquete que no depende de nada rompe el
ciclo. El core está escrito contra `RuntimeAdapter`, cada adapter
implementa `RuntimeAdapter`, y ninguno de los dos sabe que el otro
existe. Eso es lo que hace que el adapter por default se pueda
reemplazar pasando una sola opción.
Tiene un segundo efecto: como el paquete solo tiene tipos, desaparece
en tiempo de build. Depender del vocabulario compartido no cuesta nada
en runtime.
## Qué vive ahí [#qué-vive-ahí]
Dos grupos de tipos.
**El contrato de runtime** — `RuntimeAdapter`, `RuntimeServer`,
`RuntimeServeOptions`, `RuntimeHandler`, `RuntimeCapabilities`,
`RuntimeRequestContext`, y los tipos de WebSocket. Estos describen un
servidor, y son lo que un adapter implementa.
**El vocabulario de la aplicación** — `Context`, `Middleware`,
`RouteHandler`, `NextFunction`, `ProvideFn`, `BodyParser`, `Body`,
`HttpMethod`, `StandardSchemaV1` y compañía. Estos describen las cosas
que escribe tu código.
Ambos grupos están en el mismo paquete porque ambos son compartidos:
`@arcton/cors` necesita `Middleware` y `Context` sin necesitar el
core, y lo mismo cualquier middleware que publiques tú mismo.
## Por qué la interfaz es la plataforma web [#por-qué-la-interfaz-es-la-plataforma-web]
El contrato está construido sobre `Request`, `Response`, `Headers` y
`ReadableStream` en vez de sobre un objeto de request específico de
Arcton.
Esos tipos ya existen en cada runtime objetivo, están especificados de
forma independiente, y los desarrolladores ya los conocen. Un wrapper
específico del framework agregaría una capa que aprender, una capa que
mantener sincronizada con la plataforma, y una conversión en cada
límite — a cambio de muy poco. Así que `ctx.request` es un `Request`
real, y todo lo que sabes sobre la Fetch API aplica.
El único lugar donde Arcton agrega su propia forma es la respuesta,
donde `ctx.response` guarda un status y headers que siguen siendo
mutables. Un `Response` real es inmutable en las formas en que el
middleware necesita cambiarlo, así que el pipeline mantiene un objeto
mutable de staging y lo materializa — ver [Pipeline](./pipeline.mdx).
## Standard Schema, por la misma razón [#standard-schema-por-la-misma-razón]
La validation sigue el mismo principio. En vez de traer su propio
validador o depender de uno, Arcton acepta cualquier schema que
implemente [Standard Schema](https://standardschema.dev/) — la
interfaz que implementan Zod, Valibot y ArkType.
El framework nunca importa una librería de validación, a los usuarios
no se los obliga a usar la favorita del mantenedor, y un proyecto que
ya usa una sigue usándola. La interfaz es tan chica que
`StandardSchemaV1` está declarada en contracts junto con todo lo
demás, así que ni siquiera eso es una dependencia.
## Qué significa esto para tu código [#qué-significa-esto-para-tu-código]
Tipar un middleware o handler independiente significa importar desde
contracts:
```ts
import type { Middleware } from '@arcton/contracts'
export const requestId: Middleware = async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
await next()
}
```
Como el paquete es solo-tipos, ese import desaparece del output del
build.
# Adapters (/es/docs/api/adapters)
## Resumen [#resumen]
Elige un runtime pasando un adapter a `app.listen()`. `bunAdapter` es el default; pasa `nodeAdapter` para correr bajo Node.js en su lugar. Ambos implementan la interfaz [`RuntimeAdapter`](./runtime-types.mdx).
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello from Node')
app.listen({ adapter: nodeAdapter })
```
## `bunAdapter` [#bunadapter]
**Propósito** — corre una app de Arcton en Bun.
**Firma**
```ts no-check
const bunAdapter: RuntimeAdapter
```
**Comportamiento** — `name` es `'bun'`. `version` es un getter en vivo que retorna `Bun.version`. `capabilities.websocket` es `true`. Envuelve `Bun.serve()`: sirve el handler `fetch` de la app, expone `port`/`url` en el server retornado, hace auto-upgrade de cualquier ruta `ws()` registrada, y convierte un error no capturado lanzado desde el handler en una respuesta `500`, loggeado con `console.error`. `stop()` retorna `void` de forma síncrona.
**Ejemplo**
```ts
import { bunAdapter } from '@arcton/adapter-bun'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello from Bun')
app.listen({ adapter: bunAdapter })
```
## `nodeAdapter` [#nodeadapter]
**Propósito** — corre una app de Arcton en Node.js.
**Firma**
```ts no-check
const nodeAdapter: RuntimeAdapter
```
**Comportamiento** — `name` es `'node'`. `version` es un getter en vivo que retorna `process.version` sin la `v` inicial, para que coincida con el formato de número puro de Bun (por ejemplo, `'20.11.0'`, no `'v20.11.0'`). `capabilities.websocket` es `true`. Envuelve `createServer` de `node:http` para HTTP y el paquete `ws` para los upgrades de WebSocket: sirve el handler `fetch` de la app, expone `port`/`url` en el server retornado, hace auto-upgrade de cualquier ruta `ws()` registrada, y convierte un error no capturado lanzado desde el handler en una respuesta `500`, loggeado con `console.error`. `stop()` retorna una `Promise`.
**Ejemplo**
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello from Node')
const server = app.listen({ adapter: nodeAdapter, port: 0 })
await server.stop()
```
## Diferencias reales entre ambos [#diferencias-reales-entre-ambos]
Ambos adapters sirven el mismo handler `fetch` y las mismas rutas `ws()`, pero dos detalles difieren de una forma que vale la pena conocer antes de depender de ellos:
* `stop()` retorna una `Promise` en `nodeAdapter` y `void` en `bunAdapter`. `await server.stop()` es seguro con cualquiera de los dos — hacer `await` de un valor que no es una `Promise` es un no-op.
* `bunAdapter.version` es exactamente `Bun.version`; `nodeAdapter.version` es el string de versión de Node sin la `v` inicial.
Ver [Runtime support](../introduction/runtime-support.mdx) para orientación sobre cómo elegir entre ambos.
# ArctonApp (/es/docs/api/arcton-app)
Todo método de registro en `ArctonApp` devuelve la app misma, por lo que las llamadas se encadenan:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/', () => 'Hello, Arcton!')
.get('/health', () => ({ status: 'ok' }))
app.listen()
```
`config` contiene exactamente el objeto `ArctonConfig` pasado a [`Arcton()`](./arcton.mdx#arctonconfig):
```ts
import type { ArctonConfig } from '@arcton/core'
interface ArctonApp {
config: ArctonConfig
// ...
}
```
## get, post, put, delete, patch, head, options [#get-post-put-delete-patch-head-options]
**Propósito:** registra una ruta para un método HTTP. Las siete abreviaturas comparten las mismas dos formas de llamada — solo cambia el método.
**Firma**
```ts
import type { Middleware, RouteHandler, StandardSchemaV1 } from '@arcton/contracts'
import type { ArctonApp, RouteOptions } from '@arcton/core'
interface RouteMethod {
(
path: Route,
...args: [...Middleware[], RouteHandler]
): ArctonApp
<
Route extends string,
PSchema extends StandardSchemaV1 | undefined = undefined,
QSchema extends StandardSchemaV1 | undefined = undefined,
BSchema extends StandardSchemaV1 | undefined = undefined
>(
path: Route,
options: RouteOptions
): ArctonApp
}
```
**Parámetros**
**Tipo de retorno:** `ArctonApp` — la misma instancia, para encadenar llamadas.
**Comportamiento:** en la primera forma de llamada, el argumento `path` tipa `ctx.params` automáticamente a partir del literal de la ruta (`'/users/:id'` da `{ id: string }`) — ver [Context](./context.mdx). La segunda forma de llamada ([`RouteOptions`](#routeoptions)) además valida `params`/`query`/`body` contra un schema antes de ejecutar el handler — ver [Tipos de validación](./validation-types.mdx).
**Errores:** registrar el mismo `(method, path)` dos veces lanza `Duplicate route: is already registered`. Ver [Errores de registro](../errors/registration-errors.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.post('/users/:id/orders', {
handler: ctx => ({ userId: ctx.params.id })
})
app.listen()
```
## all [#all]
**Propósito:** registra una ruta que matchea con todos los métodos HTTP que soporta Arcton — los mismos siete que `get`/`post`/etc. arriba, no un comodín para verbos arbitrarios o no estándar.
**Firma:** idéntica a [`RouteMethod`](#get-post-put-delete-patch-head-options) de arriba — las mismas dos formas de llamada, los mismos genéricos.
**Tipo de retorno:** `ArctonApp`.
**Comportamiento:** registra el mismo handler para `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD` y `OPTIONS` en el path dado, en una sola llamada. Útil para delegar un path completo a un handler externo de Request/Response. Ver [Métodos HTTP](../routing/http-methods.mdx#every-method-on-one-path).
**Errores:** comparte un mismo handler entre todos los métodos de ese path — registrar un método específico en el mismo path después (o antes) tira el mismo error de "Duplicate route" que registrar ese método dos veces. Ver [Registration errors](../errors/registration-errors.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
declare const auth: { handler: (request: Request) => Promise }
const app = Arcton()
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
## RouteOptions [#routeoptions]
**Propósito:** el objeto de opciones aceptado por la segunda forma de llamada de `get`/`post`/etc., para rutas que necesitan validación de la request.
**Firma**
```ts
import type { Middleware, RouteDetail, RouteHandler } from '@arcton/contracts'
import type { ResponseSchemas } from '@arcton/core'
interface RouteOptions {
params?: PSchema
query?: QSchema
body?: BSchema
response?: ResponseSchemas
detail?: RouteDetail
middleware?: Middleware[]
handler: RouteHandler
}
```
**Parámetros**
**Comportamiento:** la validación se ejecuta en el orden params → query → body; el primer fallo corta la cadena de inmediato con un `400`. La salida del schema reemplaza el campo correspondiente de `ctx`. `ctx.body` solo existe (y solo pasa el chequeo de tipos) en una ruta que declara `body`; con `optional: true`, una request sin body se salta la validación y `ctx.body` es `undefined` (tipado `Output | undefined`) — ver [Bodies opcionales](../validation/body.mdx#optional-bodies). Con `content`, solo se aceptan los media types listados (`415` en otro caso) y `ctx.contentType` guarda el que coincidió — ver [Aceptar media types específicos](../validation/body.mdx#accepting-specific-media-types). Ver [Tipos de validación](./validation-types.mdx) y [Errores de validación](../validation/validation-errors.mdx).
`response` y `detail` son solo documentación — ver [`ResponseSchemas`](#responseschemas) y [`RouteDetail`](#routedetail) más abajo. Ninguno de los dos lo lee el pipeline de requests: un handler que devuelve algo distinto de lo que declara `response` responde exactamente igual que si `response` no existiera (ver [Response](../fundamentals/response.mdx) para lo que sí determina la respuesta). Ambos se leen a través de [`routesOf()`](#routesof) desde cualquier cosa que documente o inspeccione una app — ver [OpenAPI & Scalar](../integrations/openapi.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
params: v.object({ id: v.string() }),
body: v.object({ item: v.string() }),
handler: ctx => ({ userId: ctx.params.id, item: ctx.body.item })
})
app.listen()
```
## `ResponseSchemas` [#responseschemas]
**Propósito** — la forma que acepta `RouteOptions.response`.
**Firma**
```ts
import type { StandardSchemaV1 } from '@arcton/contracts'
type ResponseSchemas = StandardSchemaV1 | Record
```
**Comportamiento:** un `StandardSchemaV1` suelto es un atajo para `{ 200: schema }` — ambas formas se distinguen en runtime comprobando la key `'~standard'`, ya que un mapa de status → schema nunca la tiene. En cualquier caso, se normaliza a `Record` antes de llegar a [`RouteRecord.response`](./openapi.mdx#routerecord).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
// atajo de { response: { 200: UserSchema } }
app.get('/users/:id', {
response: v.object({ id: v.string() }),
handler: ctx => ({ id: ctx.params.id })
})
app.get('/orders/:id', {
response: {
200: v.object({ id: v.string() }),
404: v.object({ message: v.string() })
},
handler: ctx => ({ id: ctx.params.id })
})
app.listen()
```
## `RouteDetail` [#routedetail]
**Propósito** — la metadata de documentación que acepta `RouteOptions.detail`.
**Firma**
```ts
interface RouteDetail {
operationId?: string
summary?: string
description?: string
tags?: string[]
deprecated?: boolean
}
```
**Parámetros**
**Comportamiento:** cada campo es solo documentación — ninguno cambia cómo se matchea, valida o maneja un request. Los cinco se mapean directamente a los campos del mismo nombre de una operación de OpenAPI — ver [OpenAPI & Scalar](../integrations/openapi.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', {
detail: {
operationId: 'getUser',
summary: 'Get user',
tags: ['Users']
},
handler: ctx => ({ id: ctx.params.id })
})
app.listen()
```
## ws [#ws]
**Propósito:** registra una ruta de WebSocket.
**Firma**
```ts
import type { RuntimeWebSocketHandler } from '@arcton/contracts'
import type { ArctonApp } from '@arcton/core'
declare function ws(
path: string,
handler: RuntimeWebSocketHandler
): ArctonApp
```
**Parámetros:** `path` — se compara exactamente, sin segmentos `:param`/`*wildcard`. `handler` — un [`RuntimeWebSocketHandler`](./runtime-types.mdx).
**Tipo de retorno:** `ArctonApp`.
**Comportamiento:** las rutas ws se comparan por path exacto y no pasan por context, middleware ni providers. Ver [WebSockets](../routing/websockets.mdx) para la guía completa.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
app.listen()
```
## use [#use]
**Propósito:** registra middleware global, middleware con scope, o monta un [module](../routing/modules.mdx). Tres overloads, distinguidos por los argumentos que se pasan.
**Firma**
```ts
import type { Middleware } from '@arcton/contracts'
import type { ArctonApp } from '@arcton/core'
declare function use(middleware: Middleware): ArctonApp
declare function use(scope: string, middleware: Middleware): ArctonApp
declare function use(app: ArctonApp): ArctonApp
```
**Parámetros:** `middleware` — una función [`Middleware`](./middleware-types.mdx#middleware). `scope` — una ruta estática; el middleware solo se aplica a las rutas en esa ruta o debajo de ella. `app` — otra instancia de `ArctonApp` para montar como module.
**Tipo de retorno:** `ArctonApp`.
**Comportamiento:**
* `use(middleware)` registra middleware global — ver [Middleware global](../middleware/global.mdx).
* `use(scope, middleware)` se selecciona por ruta en el momento del registro, comparando el path propio de la ruta contra `scope` — ver [Middleware con scope](../middleware/scoped.mdx).
* `use(module)` fusiona el árbol de rutas ya construido del module dentro del árbol de esta app, en el momento del registro — ver [Modules](../routing/modules.mdx).
**Errores:** un argumento objeto que no sea un `ArctonApp` lanza `use() expects a middleware function, a (scope, middleware) pair, or an Arcton app to mount`. Un `scope` no estático lanza el mismo error de "must be a static path" que un `ArctonConfig.prefix` no estático. Ver [Errores de registro](../errors/registration-errors.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.use(async (ctx, next) => {
await next()
})
app.use('/users', async (ctx, next) => {
await next()
})
app.use(users)
app.listen()
```
## provide [#provide]
**Propósito:** compone contexto tipado sobre `ctx`, de forma plana, para cada middleware y handler registrado después.
**Firma**
```ts
import type { ProvideFn, ReservedKeys } from '@arcton/contracts'
import type { ArctonApp } from '@arcton/core'
declare function provide<
TProvided,
R extends Partial, never>> & Record
>(fn: ProvideFn): ArctonApp
```
**Parámetros:** `fn` — una [`ProvideFn`](./middleware-types.mdx#providefn) que devuelve el objeto a fusionar sobre `ctx`.
**Tipo de retorno:** `ArctonApp` — la app, con su tipo de contexto provisto ampliado por `R`.
**Comportamiento:** ver [Providers](../providers/overview.mdx) para la guía completa.
**Errores:** volver a proveer una key que ya está en `TProvided`, o una de `request`/`params`/`query`/`response`/`body`/`contentType`, es un error de compilación (vía [`ReservedKeys`](./middleware-types.mdx#reservedkeys)) — no lanza una excepción en runtime.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ db: { query: async () => [] as unknown[] } }))
.get('/users', async ctx => ctx.db.query())
app.listen()
```
## parser [#parser]
**Propósito:** registra un body parser personalizado para un media type exacto.
**Firma**
```ts
import type { BodyParser } from '@arcton/contracts'
import type { ArctonApp } from '@arcton/core'
declare function parser(
mediaType: string,
parser: BodyParser
): ArctonApp
```
**Parámetros:** `mediaType` — se compara sin distinguir mayúsculas de minúsculas, ignorando parámetros como `; charset=`. `parser` — un [`BodyParser`](./validation-types.mdx#bodyparser).
**Tipo de retorno:** `ArctonApp`.
**Comportamiento:** reemplaza un parser incorporado para el mismo media type, si existe uno. Registrar el mismo media type de nuevo reemplaza al parser anterior — es una tabla plana sin orden ni semántica de snapshot, a diferencia de `use()`/`provide()`. Solo se consulta para una ruta que declara un schema `body`, y registrar un parser no hace que una ruta acepte su media type — hay que listarlo en `body.content`. Ver [Body parsers](../validation/body-parsers.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.parser('text/csv', async request => {
const text = await request.text()
return text.trim().split('\n')
})
app.listen()
```
## onError [#onerror]
**Propósito:** registra un handler para un error que de otro modo quedaría sin capturar — de un provider, un middleware, la validación, o el propio handler de la ruta.
**Firma**
```ts
import type { ErrorHandler, QueryParams, RouteParams } from '@arcton/contracts'
import type { ArctonApp } from '@arcton/core'
declare function onError(
handler: ErrorHandler
): ArctonApp
```
**Parámetros:** `handler` — un [`ErrorHandler`](./middleware-types.mdx#errorhandler).
**Tipo de retorno:** `ArctonApp`.
**Comportamiento:** solo un handler a la vez — una llamada posterior reemplaza a la anterior — y solo se consulta el de la instancia cuyo propio `listen()` termina sirviendo el request; uno registrado en un módulo montado con `use()` no tiene ningún efecto. Devolver un valor o una `Response` maneja el error; no devolver nada lo declina, y se aplica el comportamiento por defecto de Arcton (`400`/`415` para un `ValidationError` o un `Content-Type` de body no soportado; en cualquier otro caso el error se propaga al adapter). `ctx.response.status` usa `500` por defecto (`400`/`415` para esos dos errores de request) si el handler no asigna uno, sin sobrescribir un status que algún paso ya haya asignado antes del throw. Si el propio handler lanza un error, ese error se propaga de la misma forma en que lo haría un error no capturado sin ningún handler registrado. Sin `onError()`, un error no capturado se sigue propagando al adapter del runtime tal como describe [Errores no capturados](../errors/uncaught-errors.mdx) — esto es opt-in. Ver [Global error handler](../errors/global-error-handler.mdx) para la guía completa.
**Ejemplo**
```ts
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.onError((err, ctx) => {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
return { code: 'INTERNAL_SERVER_ERROR', message: 'Internal Server Error' }
})
app.listen()
```
## listen [#listen]
**Propósito:** comienza a atender requests.
**Firma**
```ts
import type { ArctonListenOptions } from '@arcton/core'
import type { RuntimeServer } from '@arcton/contracts'
declare function listen(options?: ArctonListenOptions): RuntimeServer
```
**Comportamiento:** ver [`listen()`](./listen.mdx) para la referencia completa, incluyendo el `RuntimeServer` devuelto.
## `routesOf()` [#routesof]
**Propósito:** la vista de solo lectura de cada ruta registrada en una app — los schemas y la metadata que declaró cada una, y su path final (con prefijo). Lo que permite que un paquete fuera de `@arcton/core` — [`@arcton/openapi`](./openapi.mdx), o cualquier otra cosa que documente o inspeccione una app — vea los contratos de las rutas sin que la app exponga directamente su router o su pipeline.
**Firma**
```ts
import type { RouteRecord } from '@arcton/contracts'
import type { ArctonApp } from '@arcton/core'
declare function routesOf(app: ArctonApp): readonly RouteRecord[]
```
**Parámetros:** `app` — cualquier instancia de `ArctonApp`, montada o no.
**Tipo de retorno:** `readonly RouteRecord[]` — ver [`RouteRecord`](./openapi.mdx#routerecord).
**Comportamiento:** un record por cada método bajo el que se registró una ruta — `app.all()` produce siete, nunca un record de "cualquier método" — en el orden de registro, cada uno con su path final (con todo prefijo de montaje ya aplicado). Los records propios de un module se incluyen una vez que se monta con `use()`, con el mismo prefijo que su árbol de rutas; llamar a `routesOf()` sobre el module mismo sigue devolviendo sus records solo con su propio prefijo, sin verse afectado por dónde termine montándose. Una ruta `ws()` no produce ningún record, al no tener contrato que describir. Las respuestas que da un middleware `openapi()` nunca se incluyen, así que un documento nunca se documenta a sí mismo.
**Errores:** lanza `routesOf() expects an Arcton app` para cualquier cosa que no sea una.
**Ejemplo**
```ts
import { Arcton, routesOf } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/users/:id', {
params: v.object({ id: v.string() }),
handler: ctx => ({ id: ctx.params.id })
})
for (const route of routesOf(app)) {
console.log(route.method, route.path)
}
// GET /users/:id
```
## HttpMethod [#httpmethod]
**Propósito:** la unión de métodos HTTP a la que corresponden las abreviaturas de rutas de `ArctonApp`.
**Firma**
```ts
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'
```
**Comportamiento:** se usa en cualquier lugar donde un método necesite nombrarse fuera de llamar directamente a `app.get`/`app.post`/etc. — por ejemplo, el header `Allow` en una respuesta `405` lista los `HttpMethod` que sí soporta la ruta encontrada. Ver [Métodos HTTP](../routing/http-methods.mdx).
# Arcton (/es/docs/api/arcton)
Toda aplicación Arcton comienza con una sola llamada a esta función:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen()
```
## Arcton() [#arcton]
**Propósito:** crea una nueva instancia de aplicación — un [`ArctonApp`](./arcton-app.mdx) — sobre la que registras rutas, middleware y providers.
**Firma**
```ts
import type { ArctonApp, ArctonConfig } from '@arcton/core'
declare function Arcton(config?: ArctonConfig): ArctonApp<{}>
```
**Parámetros**
**Tipo de retorno:** un [`ArctonApp<{}>`](./arcton-app.mdx) sin contexto provisto todavía — [`provide()`](./arcton-app.mdx#provide) lo hace crecer a medida que registras providers.
**Comportamiento:** cada llamada a `Arcton()` crea una instancia independiente, con su propio árbol de rutas, middleware global y body parsers. Llamarla más de una vez — por ejemplo, para construir un [module](../routing/modules.mdx) que luego se monta con `app.use(module)` — es la forma normal de componer una aplicación a partir de piezas más pequeñas.
**Errores:** ninguno directamente. Un `config.prefix` que no sea una ruta estática lanza una excepción en el momento de la construcción — ver `ArctonConfig` más abajo.
## ArctonConfig [#arctonconfig]
**Propósito:** el objeto de configuración que se pasa a `Arcton()`.
**Firma**
```ts
interface ArctonConfig {
prefix?: string
}
```
**Parámetros**
**Comportamiento:** `prefix` debe ser una ruta estática — un segmento `:param` o `*wildcard` lanza una excepción al crear la instancia. `'/'` y un `prefix` omitido equivalen a no tener prefix. Ver [Configuración de la app](../configuration/app-config.mdx) para la guía completa, incluyendo cómo se componen los prefixes entre modules montados.
**Errores:** un prefix no estático lanza `Prefix "" must be a static path — dynamic/wildcard segments aren't supported (e.g. app.use('/api', mw), not app.use('/api/:id', mw))`. Ver [Errores de registro](../errors/registration-errors.mdx).
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api' })
app.get('/users', () => [])
app.listen()
```
# CLI (/es/docs/api/cli)
## Resumen [#resumen]
Scaffoldea un nuevo proyecto de forma interactiva:
```bash
bunx arcton create my-app
```
o mediante la convención de scaffolding del package manager, que resuelve al mismo flujo a través del paquete separado `create-arcton`:
```bash
bun create arcton my-app
npm create arcton my-app
pnpm create arcton my-app
```
Pasar el nombre como argumento (como arriba) se salta el prompt del nombre; corriéndolo sin uno lo pregunta interactivamente.
## `arcton create` [#arcton-create]
**Propósito** — scaffoldea interactivamente un nuevo proyecto de Arcton: elegir un nombre de proyecto, un runtime, y un package manager, y luego opcionalmente instalar las dependencias.
**Firma**
```bash
arcton create [name]
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | `string` (opcional) | Nombre del directorio del proyecto. Debe contener solo letras, dígitos, puntos, guiones y guiones bajos. Se pregunta interactivamente si se omite. |
**Comportamiento** — el flujo, en orden:
1. Pregunta por un nombre de proyecto (se salta si se pasó como argumento).
2. Pregunta por un runtime: Bun o Node.js.
3. Pregunta por un package manager: `bun`, `pnpm`, o `npm` (por defecto `bun` si el runtime elegido es Bun, si no `npm`).
4. Si el directorio destino ya existe y no está vacío, pide confirmar si sobrescribirlo.
5. Copia el template del runtime elegido al directorio destino y setea el `name` del proyecto en su `package.json`.
6. Pregunta si instalar las dependencias ahora (por defecto sí), y corre el comando de instalación correspondiente si la respuesta es afirmativa.
7. Imprime los próximos pasos a seguir.
Esto se expone tanto como el subcomando `arcton create` (desde el subpath export `arcton/create` del paquete `arcton`) como, de forma independiente, `create-arcton` — un paquete cuyo único trabajo es satisfacer la convención `create-` de la que dependen `npm create arcton` / `pnpm create arcton` / `bun create arcton`, re-exportando la misma implementación.
**Ejemplo**
```bash
bunx arcton create my-app
```
```bash
cd my-app
bun install
bun run dev
```
## Templates [#templates]
Hay dos templates de runtime disponibles; ambos scaffoldean un proyecto que depende de `@arcton/core`.
### Template de Bun [#template-de-bun]
Scripts de `package.json`:
```json
{
"scripts": {
"dev": "bun --hot src/index.ts",
"start": "bun run src/index.ts",
"compile": "bun build --compile --minify --sourcemap ./src/index.ts --outfile arcton-app"
}
}
```
`src/index.ts`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen()
```
### Template de Node [#template-de-node]
Scripts de `package.json`:
```json
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc --build",
"start": "node dist/index.js"
}
}
```
`src/index.ts`:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen({ adapter: nodeAdapter })
```
Ver [Installation](../getting-started/installation.mdx) para los prerequisitos y [Development](../getting-started/development.mdx) para el uso diario de estos scripts.
# Context (/es/docs/api/context)
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => {
return { id: ctx.params.id, page: ctx.query.page ?? '1' }
})
app.listen()
```
Todo handler, [provider](../providers/overview.mdx) y función de [middleware](../middleware/overview.mdx) recibe un `Context` como primer argumento (el middleware también recibe un `next`). Esta página es la referencia de tipos; ver [Context](../fundamentals/context.mdx) para la guía orientada al concepto.
## Context [#context]
**Propósito:** la forma completa de `ctx` en un punto dado del pipeline.
**Firma**
```ts
import type { BaseContext, QueryParams, RouteParams } from '@arcton/contracts'
type Context =
BaseContext
& TBody & TProvided
```
**Parámetros**
**Comportamiento:** los valores provistos quedan planos sobre `ctx` — no hay namespace. `params` se infiere del literal de ruta pasado a `get`/`post`/etc.: `'/users/:id'` da `{ id: string }`, una ruta sin params da `Record`, y un path pasado como variable `string` no literal da `Record`. `query` es `Record` por defecto, construido de forma perezosa en el primer acceso — las keys repetidas conservan el último valor, y una key sin valor se lee como `''`.
## BaseContext [#basecontext]
**Propósito:** los campos presentes en todo `Context`, sin importar qué se haya provisto o validado.
**Firma**
```ts
import type { ResponseContext } from '@arcton/contracts'
interface BaseContext {
request: Request
params: P
query: Q
response: ResponseContext
}
```
**Comportamiento:** `request` es el `Request` crudo, sin modificar. `response` se describe más abajo.
## ResponseContext [#responsecontext]
**Propósito:** el estado mutable de la response disponible antes de que el body finalice.
**Firma**
```ts
interface ResponseContext {
status?: number
headers: Headers
}
```
**Comportamiento:** `ctx.response` comienza como este objeto plano y se materializa en un `Response` real en el momento en que el body finaliza, en cualquier capa (el handler retorna, un step corta la cadena, o una capa reemplaza el body después de `next()`). Antes de la materialización, se puede asignar `ctx.response.status` directamente. Después de la materialización, mutar los headers sigue funcionando y llega al cliente, pero `status` ya no acepta asignación. Ver [Response](../fundamentals/response.mdx).
Configura `ctx.response.status` desde el handler, o desde middleware antes de llamar a `await next()`. Configurarlo después lanza una excepción, porque para ese momento el body ya se materializó en un `Response` real.
## RouteParams [#routeparams]
**Propósito:** la forma por defecto de `ctx.params` para una ruta sin schema de params.
**Firma**
```ts
type RouteParams = Record
```
## QueryParams [#queryparams]
**Propósito:** la forma por defecto de `ctx.query` para una ruta sin schema de query.
**Firma**
```ts
type QueryParams = Record
```
## Body [#body]
**Propósito:** la unión de valores que un handler o middleware puede retornar.
**Firma**
```ts
type Body =
| object
| string
| ArrayBufferView
| ArrayBuffer
| Blob
| FormData
| URLSearchParams
| ReadableStream
| Response
```
**Comportamiento:** cada variante se mapea a una response HTTP distinta — ver [Response](../fundamentals/response.mdx) para la tabla completa de mapeo, incluyendo cómo se derivan el status y los headers en cada caso.
# CORS (/es/docs/api/cors)
## Resumen [#resumen]
Agrega headers de CORS y maneja preflight requests con un solo middleware global:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: ['https://app.example.com'],
credentials: true
})
)
app.get('/', () => ({ hello: 'world' }))
app.listen()
```
Como `cors()` retorna middleware global sin scope, también cubre las respuestas `404`/`405` (ver [Global middleware](../middleware/global.mdx)).
## `cors()` [#cors]
**Propósito** — construye un middleware de CORS a partir de un conjunto de opciones.
**Firma**
```ts no-check
function cors(options?: CorsOptions): Middleware
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | ------------- | -------------------------------------------------- |
| `options` | `CorsOptions` | Opcional. Ver más abajo los campos y sus defaults. |
**Tipo de retorno** — un [`Middleware`](./middleware-types.mdx), pensado para pasarse a `app.use()`.
**Errores** — lanza un `TypeError` en el momento de configuración — no por request — cuando `origin` es `'*'` (su default) y `credentials` es `true`:
```
CORS: credentials cannot be enabled when origin is "*"
```
Una respuesta con credenciales no puede usar el origin wildcard; el navegador la rechaza.
**Comportamiento**
* Un request sin header `Origin` pasa directo — no es un request de CORS.
* Un origin permitido no-wildcard se devuelve tal cual en `Access-Control-Allow-Origin`, y se agrega `Vary: Origin`.
* Un origin no permitido: el request continúa normalmente y no se agrega ningún header de CORS — Arcton no lo bloquea del lado del servidor; el navegador aplica la política de CORS del lado del cliente.
* Un preflight real (un request `OPTIONS` que trae `Access-Control-Request-Method`) corta la cadena con `204` y los headers de CORS calculados. Si se omiten `methods`/`allowedHeaders`, la respuesta repite el propio `Access-Control-Request-Method` / `Access-Control-Request-Headers` del request.
* `preflight: false` desactiva el corte automático con `204` — un preflight real entonces llega a `next()` como cualquier otro request — pero los headers de CORS igual se agregan a lo que la ruta termine devolviendo.
* `credentials: true` agrega `Access-Control-Allow-Credentials: true`.
* Un `exposedHeaders` no vacío setea `Access-Control-Expose-Headers`, unido con `, `.
## `CorsOptions` [#corsoptions]
**Propósito** — el objeto de opciones que acepta `cors()`.
**Firma**
```ts no-check
interface CorsOptions {
origin?: CorsOrigin
methods?: string[]
allowedHeaders?: string[]
exposedHeaders?: string[]
credentials?: boolean
maxAge?: number
preflight?: boolean
}
```
**Campos**
| Campo | Tipo | Default | Descripción |
| ---------------- | ------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `origin` | `CorsOrigin` | `'*'` | Qué origins están permitidos. Ver `CorsOrigin` más abajo. |
| `methods` | `string[]` | — | Se envía como `Access-Control-Allow-Methods` en un preflight. Si se omite, el preflight repite el propio `Access-Control-Request-Method` del request. |
| `allowedHeaders` | `string[]` | — | Se envía como `Access-Control-Allow-Headers` en un preflight. Si se omite, el preflight repite el propio `Access-Control-Request-Headers` del request. |
| `exposedHeaders` | `string[]` | — | Se envía como `Access-Control-Expose-Headers` en la respuesta real. |
| `credentials` | `boolean` | `false` | Agrega `Access-Control-Allow-Credentials: true`. No se puede combinar con `origin: '*'`. |
| `maxAge` | `number` | — | Se envía como `Access-Control-Max-Age` en un preflight. |
| `preflight` | `boolean` | `true` | Si un preflight real se responde automáticamente con `204`. |
## `CorsOrigin` [#corsorigin]
**Propósito** — la forma que acepta `CorsOptions.origin`.
**Firma**
```ts
type CorsOrigin =
| '*'
| string
| string[]
| ((origin: string, request: Request) => boolean)
```
**Comportamiento** — `'*'` permite cualquier origin (y no se puede combinar con `credentials: true`). Un `string` permite exactamente ese origin. Un `string[]` permite cualquier origin de la lista. Una función recibe el valor del header `Origin` del request y el `Request` mismo, y retorna si está permitido — evaluada por cada request.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: (origin, request) =>
origin.endsWith('.example.com') || request.headers.has('x-internal')
})
)
app.get('/status', () => ({ ok: true }))
app.listen()
```
# HTTP Errors (/es/docs/api/http-errors)
## Resumen [#resumen]
Lanzá un error ya armado en vez de construir a mano `ctx.response.status = ...; return {...}` en cada lugar donde una request puede fallar:
```ts
import { Arcton, Http } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.listen()
```
Por sí solo esto sigue siendo un error no capturado — convertirlo en una respuesta queda de tu lado, igual que con cualquier otro throw. Ver [Respondiendo con errores](../errors/responding-with-errors.mdx#throw-a-ready-made-httperror-instead-of-hand-rolling-one) para el patrón try/catch que mapea `status`/`code`/`body` de `HttpError` sobre `ctx.response`.
## `HttpError` [#httperror]
**Propósito** — la clase de error que retorna cada factory de `Http` de abajo; se instancia directamente para un status sin factory con nombre.
**Firma**
```ts no-check
class HttpError extends Error {
constructor(status: number, code: string, message: string, body?: unknown)
readonly status: number
readonly code: string
readonly body?: unknown
}
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `status` | `number` | El status HTTP, por ejemplo `451`. |
| `code` | `string` | Una etiqueta estable y legible por máquina, por ejemplo `'UNAVAILABLE_FOR_LEGAL_REASONS'`. Segura para que un cliente haga switch sobre ella, a diferencia de `message`. |
| `message` | `string` | Se pasa al `message` propio de `Error`. |
| `body` | `unknown` | Opcional. El valor exacto que un catch debería devolver en vez del shape default `{ code, message }`. |
**Comportamiento** — `HttpError` lleva estos campos pero no hace nada con ellos por sí sola; nada en el pipeline de Arcton captura un `HttpError` automáticamente (ver [Errores no capturados](../errors/uncaught-errors.mdx)).
**Ejemplo**
```ts
import { HttpError } from '@arcton/core'
throw new HttpError(451, 'UNAVAILABLE_FOR_LEGAL_REASONS', 'Unavailable For Legal Reasons')
```
## `Http` [#http]
**Propósito** — un namespace de atajos listos para lanzar, uno por cada status común. Cada uno es una función simple — se llama, no se instancia con `new` — y retorna un `HttpError`.
**Firma**
```ts no-check
type StatusErrorFactory = (message?: string, body?: unknown) => HttpError
const Http: Record
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | --------- | ----------------------------------------------------------------------------------------------------- |
| `message` | `string` | Opcional. Por default usa la frase de razón del status (ver la tabla de abajo). |
| `body` | `unknown` | Opcional. El valor exacto que un catch debería devolver en vez del shape default `{ code, message }`. |
**Tipo de retorno** — un [`HttpError`](#httperror).
**Factories**
| Factory | Status | `code` | `message` por default |
| -------------------------- | ------ | ------------------------- | --------------------- |
| `Http.BadRequest` | `400` | `'BAD_REQUEST'` | Bad Request |
| `Http.Unauthorized` | `401` | `'UNAUTHORIZED'` | Unauthorized |
| `Http.Forbidden` | `403` | `'FORBIDDEN'` | Forbidden |
| `Http.NotFound` | `404` | `'NOT_FOUND'` | Not Found |
| `Http.MethodNotAllowed` | `405` | `'METHOD_NOT_ALLOWED'` | Method Not Allowed |
| `Http.Conflict` | `409` | `'CONFLICT'` | Conflict |
| `Http.Gone` | `410` | `'GONE'` | Gone |
| `Http.UnprocessableEntity` | `422` | `'UNPROCESSABLE_ENTITY'` | Unprocessable Entity |
| `Http.TooManyRequests` | `429` | `'TOO_MANY_REQUESTS'` | Too Many Requests |
| `Http.InternalServerError` | `500` | `'INTERNAL_SERVER_ERROR'` | Internal Server Error |
| `Http.ServiceUnavailable` | `503` | `'SERVICE_UNAVAILABLE'` | Service Unavailable |
`throw Http.NotFound` — la referencia a la función pelada, sin `()` — lanza
la función misma, no un `HttpError`. Un bloque catch que chequea
`instanceof HttpError` no la va a reconocer, y llega al adapter como un
`500` sin diferenciar. Siempre hay que llamar a la factory.
**Ejemplo**
```ts
import { Http } from '@arcton/core'
throw Http.Conflict('Email already registered', { field: 'email' })
```
## `ValidationError` [#validationerror]
**Propósito** — el error que Arcton lanza cuando falla un esquema de `params`, `query` o `body` (o no se puede interpretar el body). Llega a [`app.onError()`](./arcton-app.mdx#onerror) como cualquier otro error.
**Firma**
```ts no-check
class ValidationError extends HttpError {
constructor(issues: ReadonlyArray)
readonly issues: ReadonlyArray
}
```
**Comportamiento** — `status` es `400`, `code` es `'VALIDATION_FAILED'` y `body` es `{ issues }`. `issues` es exactamente el array que devolvió la librería de esquemas, sin modificar. Sin `onError()` (o con uno que no devuelve nada), responde `400` con `{ "issues": [...] }`. Ver [Errores de validación](../validation/validation-errors.mdx).
**Ejemplo**
```ts
import { Arcton, ValidationError } from '@arcton/core'
const app = Arcton()
app.onError(err => {
if (err instanceof ValidationError) return { issues: err.issues }
})
```
# listen() (/es/docs/api/listen)
`listen()` es la última llamada en una aplicación Arcton:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
const server = app.listen({ port: 3000 })
console.log(`Listening on ${server.url}`)
```
Ver [Opciones de listen](../configuration/listen-options.mdx) para la guía orientada al uso.
## listen [#listen]
**Propósito:** inicia el servidor a través del [adapter](./adapters.mdx) elegido.
**Firma**
```ts
import type { ArctonListenOptions } from '@arcton/core'
import type { RuntimeServer } from '@arcton/contracts'
declare function listen(options?: ArctonListenOptions): RuntimeServer
```
**Parámetros:** un `ArctonListenOptions` opcional, documentado más abajo.
**Tipo de retorno:** [`RuntimeServer`](#runtimeserver).
**Comportamiento:** imprime un banner de arranque — el logo figlet de Arcton, la versión de Arcton, el nombre y versión del runtime, el `env`, y la URL de escucha — y luego devuelve un `RuntimeServer`. Las rutas, y las llamadas a `use()` y `provide()` hechas después de `listen()`, no afectan a las requests que ya fluyen a través de rutas registradas antes, ya que el pipeline de cada ruta queda fijado en un snapshot al momento del registro. A menos que `gracefulShutdown` sea `false`, también registra el servidor devuelto en un coordinador de apagado process-wide, para que una `SIGTERM`/`SIGINT` lo drene — ver [Apagado elegante](../configuration/listen-options.mdx#apagado-elegante).
**Errores:** si se registró alguna ruta [`ws()`](./arcton-app.mdx#ws) y el `capabilities.websocket` del adapter elegido es `false`, `listen()` lanza `Runtime "" does not support WebSocket routes.`. Ambos adapters incluidos — [`bunAdapter` y `nodeAdapter`](./adapters.mdx) — soportan WebSockets, así que esto solo importa con un adapter personalizado. También lanza si `shutdownTimeout` se pasa pero no es un número positivo y finito.
## ArctonListenOptions [#arctonlistenoptions]
**Propósito:** el objeto de opciones aceptado por `listen()`.
**Firma**
```ts
import type { RuntimeAdapter } from '@arcton/contracts'
interface ArctonListenOptions {
port?: number
hostname?: string
adapter?: RuntimeAdapter
env?: string
maxBodySize?: number
gracefulShutdown?: boolean
shutdownTimeout?: number
}
```
**Parámetros**
**Comportamiento:** ver [Entorno](../configuration/environment.mdx) para lo que hace `env` (y solo eso), [Tipos de runtime](./runtime-types.mdx) para la interfaz `RuntimeAdapter`, y [Adapters](./adapters.mdx) para los valores `bunAdapter`/`nodeAdapter`.
`gracefulShutdown` y `shutdownTimeout` controlan el manejo process-wide de `SIGTERM`/`SIGINT` descrito en [Apagado elegante](../configuration/listen-options.mdx#apagado-elegante). `gracefulShutdown: false` excluye por completo a una llamada de `listen()` dada — útil cuando la aplicación anfitriona maneja las señales del proceso por su cuenta, ya que un apagado elegante termina llamando a `process.exit()`, lo que termina todo el proceso, no solo este servidor.
## RuntimeServer [#runtimeserver]
**Propósito:** el handle que devuelve `listen()` para el servidor en ejecución.
**Firma**
```ts
interface RuntimeServer {
readonly port: number
readonly url: URL
stop(closeActiveConnections?: boolean): void | Promise
}
```
**Parámetros**
**Comportamiento:** `port` y `url` reflejan la dirección realmente vinculada — útil cuando `port: 0` eligió una libre. `stop()` apaga el servidor; devuelve `void` en el [adapter de Bun](./adapters.mdx) y una `Promise` en el [adapter de Node](./adapters.mdx). Este es el tipo que se usa en toda la sección de [Testing](../testing/overview.mdx) para levantar un servidor en `port: 0`, ejercitarlo con llamadas `fetch` reales, y luego apagarlo.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
const res = await fetch(server.url)
console.log(res.status, server.port)
await server.stop()
```
# Logger (/es/docs/api/logger)
## Resumen [#resumen]
Loguea una línea por request, sin ninguna dependencia en runtime:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger())
app.get('/', () => ({ hello: 'world' }))
app.listen()
```
`@arcton/logger` es solo `app.use()`. Ver
[Logging](../integrations/logger.mdx) para la guía orientada al uso.
## `logger()` [#logger]
**Propósito** — construye un middleware de logging de requests.
**Firma**
```ts no-check
function logger(options?: LoggerOptions): ArctonLogger
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | --------------- | -------------------------------------------- |
| `options` | `LoggerOptions` | Opcional. Ver abajo cada campo y su default. |
**Tipo de retorno** — un [`ArctonLogger`](#arctonlogger): un
[`Middleware`](./middleware-types.mdx#middleware) con una propiedad
`.logger` agregada, pensado para pasarse a `app.use()`.
**Comportamiento**
* Lee `ctx.request.method` y el `pathname` de la URL del request (sin el
query string) antes de llamar a `next()`.
* Con `pretty: false` (el default): una vez que `next()` resuelve, loguea
una línea de JSON con `method`, `path`, `status` (`ctx.response.status`,
`200` por defecto) y `durationMs` — a `error` si el status es `5xx`,
`warn` si es `4xx`, `info` en cualquier otro caso.
* Con `pretty: true`: loguea una línea `→` cuando llega el request, y una
línea `←` cuando termina (o una línea `ERR` si nada aguas abajo capturó
un error lanzado) — ver [Modo pretty](../integrations/logger.mdx#pretty-mode).
* Si `next()` rechaza — nada aguas abajo capturó el error — loguea una
línea a `error` (JSON) o una línea `ERR` (pretty), con el error adjunto,
y vuelve a lanzar el mismo error sin modificarlo. No se loguea ninguna
línea de finalización después.
* `level` filtra ambos formatos de la misma manera: `'silent'` no imprime
nada, y un nivel por encima del que tendría una línea dada la descarta.
* Nunca corta la cadena ni toca `ctx.response` por sí mismo — una ruta se
comporta exactamente igual que sin ningún logger registrado.
**Errores** — ninguno.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger({ level: 'debug', pretty: true }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.get('/boom', () => {
throw new Error('kaboom')
})
app.listen()
```
## `createLogger()` [#createlogger]
**Propósito** — construye un [`Logger`](#logger) independiente, sin
depender de ningún request. `logger()` construye uno de estos
internamente para su middleware de logging de requests, pero es igual de
usable en un background job o al arrancar.
**Firma**
```ts no-check
function createLogger(options?: LoggerOptions): Logger
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | --------------- | -------------------------------------------- |
| `options` | `LoggerOptions` | Opcional. Ver abajo cada campo y su default. |
**Tipo de retorno** — un [`Logger`](#logger).
**Errores** — ninguno.
**Ejemplo**
```ts
import { createLogger } from '@arcton/logger'
const log = createLogger({ level: 'debug' })
log.info('server starting', { pid: process.pid })
const dbLog = log.child({ component: 'database' })
dbLog.info('query executed', { table: 'users' })
```
## `Logger` [#logger-1]
**Propósito** — la interfaz que comparten cada método de logging (`trace`
hasta `fatal`) y `child()`, devuelta tanto por `createLogger()` como en
`.logger` de un [`ArctonLogger`](#arctonlogger).
**Firma**
```ts
interface Logger {
trace(msg: string, data?: Record): void
debug(msg: string, data?: Record): void
info(msg: string, data?: Record): void
warn(msg: string, data?: Record): void
error(msg: string, data?: Record): void
fatal(msg: string, data?: Record): void
child(bindings: Record): Logger
}
```
**Parámetros**
**Comportamiento:** una llamada por debajo del `level` configurado retorna
de inmediato — no se construye ningún record, no se paga ningún costo de
`Date`/serialización. `data` en una llamada dada sobrescribe un campo de
`bindings` del mismo nombre solo para ese record. Un valor bajo `err` (o
cualquier key) que sea un `Error` se serializa a `{ name, message, stack }`,
ya que `JSON.stringify` solo reduce un `Error` plano a `{}`. `child(bindings)`
devuelve un nuevo `Logger` con `bindings` mezclado sobre el suyo propio —
de forma recursiva, así que un nieto lleva todo lo que sus ancestros
agregaron — sin mutar el logger sobre el que se llamó.
**Ejemplo**
```ts
import { createLogger } from '@arcton/logger'
const log = createLogger()
log.warn('cache miss', { key: 'user:42' })
const requestLog = log.child({ requestId: 'req_1' })
requestLog.info('handled') // incluye requestId: 'req_1'
```
## `LoggerOptions` [#loggeroptions]
**Propósito** — el objeto de opciones aceptado tanto por `logger()` como
por `createLogger()`.
**Firma**
```ts
import type { LevelWithSilent } from '@arcton/logger'
interface LoggerOptions {
level?: LevelWithSilent
pretty?: boolean
sink?: (line: string) => void
bindings?: Record
}
```
**Campos**
| Campo | Tipo | Default | Descripción |
| ---------- | ------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `level` | `LevelWithSilent` | `'info'` | Nivel mínimo a loguear. Cualquier cosa por debajo se descarta antes de siquiera construir un record. |
| `pretty` | `boolean` | `false` | Formatea para que lo lea una persona en vez de JSON separado por líneas. |
| `sink` | `(line: string) => void` | escribe a `process.stdout` si existe, `console.log` si no | Dónde se escribe cada línea formateada. |
| `bindings` | `Record` | `{}` | Campos mezclados en cada record — lo que `child()` agrega, no un reemplazo. |
**Comportamiento:** el `sink` por defecto se resuelve una sola vez, cuando
se carga `@arcton/logger` — `process.stdout.write` en Node/Bun,
`console.log` en cualquier lugar donde `process` no exista (un Worker).
Pasá el tuyo propio para redirigir la salida — a un archivo, una captura
de test, otro servicio — sin cambiar nada más.
## `LogLevel` y `LevelWithSilent` [#loglevel-y-levelwithsilent]
**Propósito** — los nombres de nivel que acepta un `Logger`, y el conjunto
más amplio que acepta `LoggerOptions.level`.
**Firma**
```ts
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
type LevelWithSilent = LogLevel | 'silent'
```
**Comportamiento:** ordenados como se listan, `trace` el más bajo — una
llamada se escribe cuando el rango de su propio nivel es igual o mayor que
el del mínimo configurado. `'silent'` supera a cualquier nivel real, así
que nada pasa el filtro.
## `ArctonLogger` [#arctonlogger]
**Propósito** — lo que devuelve `logger()`.
**Firma**
```ts no-check
type ArctonLogger = Middleware & {
readonly logger: Logger
}
```
**Comportamiento** — una función [`Middleware`](./middleware-types.mdx#middleware)
común, así que `app.use(logger())` funciona exactamente igual que
[`app.use(cors())`](./cors.mdx). `.logger` es la misma instancia de
[`Logger`](#logger) que usa el middleware para loguear, para loguear
cualquier cosa fuera del ciclo request/response:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
const log = logger()
app.use(log)
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
log.logger.info(`listening on ${server.url}`)
```
# Tipos de middleware (/es/docs/api/middleware-types)
Un [`Middleware`](#middleware) es simplemente una función — sin clase, sin decorador, nada más que pasarla a [`app.use()`](./arcton-app.mdx#use) o a una ruta:
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const logger: Middleware = async (ctx, next) => {
console.log(ctx.request.method, ctx.request.url)
await next()
}
const app = Arcton()
app.use(logger)
app.get('/', () => 'ok')
app.listen()
```
## Middleware [#middleware]
**Propósito:** la forma de toda función de middleware — global, con scope, o route middleware.
**Firma**
```ts
import type { Body, Context, NextFunction, QueryParams, RouteParams } from '@arcton/contracts'
type Middleware = (
ctx: Context
,
next: NextFunction
) => Promise
| Body | void
```
**Comportamiento:** el orden de los parámetros genéricos — `P, Q, TBody, TProvided` — es estructural: coincide con el propio orden de [`Context`](./context.mdx). El código antes de `await next()` corre de ida; el código después corre de vuelta. Retornar un valor sin llamar a `next()` corta la cadena del pipeline — nada más abajo se ejecuta. Ver [Orden de ejecución](../middleware/execution-order.mdx).
## NextFunction [#nextfunction]
**Propósito:** avanza el pipeline al siguiente step.
**Firma**
```ts
type NextFunction = () => Promise
```
**Comportamiento:** llama al siguiente middleware (o al handler, si no queda ninguno) y se resuelve una vez que todo lo que sigue haya terminado.
## RouteHandler [#routehandler]
**Propósito:** la forma del handler final de una ruta.
**Firma**
```ts
import type { Body, Context, QueryParams, RouteParams } from '@arcton/contracts'
type RouteHandler = (
ctx: Context
) => (Body | void) | Promise
```
**Comportamiento:** la misma forma que [`Middleware`](#middleware), sin `next` — un handler siempre corre al final, así que no tiene nada que llamar. Este es el tipo del argumento final de `get`/`post`/etc. y de `RouteOptions.handler`.
## ErrorHandler [#errorhandler]
**Propósito:** la forma del handler que recibe [`app.onError()`](./arcton-app.mdx#onerror).
**Firma**
```ts
import type { Body, Context, QueryParams, RouteParams } from '@arcton/contracts'
type ErrorHandler = (
err: unknown,
ctx: Context
) => (Body | void) | Promise
```
**Comportamiento:** la misma forma que [`RouteHandler`](#routehandler), con el error capturado como primer argumento. `err` es `unknown`, no `Error` — un valor lanzado en JavaScript no tiene por qué serlo. Ver [Global error handler](../errors/global-error-handler.mdx).
## MatchResult [#matchresult]
**Propósito:** el resultado de hacer match entre un método y un path contra el árbol de rutas.
**Firma**
```ts
import type { HttpMethod, RouteHandler, RouteParams } from '@arcton/contracts'
type MatchResult =
| { matched: true; handler: RouteHandler; params: RouteParams }
| { notFound: true }
| { methodNotAllowed: true; allowed: HttpMethod[] }
```
**Comportamiento:** el valor de retorno de `Router.match()`, descrito a continuación. El código de la aplicación no construye ni lee esto directamente — se expone para quien implemente un [`RuntimeAdapter`](./runtime-types.mdx) personalizado.
## Router [#router]
**Propósito:** la interfaz interna que usa `ArctonApp` para resolver una request a un handler.
**Firma**
```ts
import type { HttpMethod, MatchResult } from '@arcton/contracts'
interface Router {
match(method: HttpMethod, url: string): MatchResult
}
```
**Comportamiento:** ver [Precedencia](../routing/precedence.mdx) para las reglas de matching — static le gana a dynamic, que le gana a wildcard, con backtracking.
## ReservedKeys [#reservedkeys]
**Propósito:** las keys que [`provide()`](./arcton-app.mdx#provide) rechaza agregar.
**Firma**
```ts
import type { BaseContext } from '@arcton/contracts'
type ReservedKeys =
| keyof BaseContext
| 'body'
| 'contentType'
| keyof TProvided
```
**Comportamiento:** cubre los campos base de `Context` (`request`/`params`/`query`/`response`), `'body'`, `'contentType'`, y cualquier key ya provista antes en la cadena. Volver a proveer una de estas es un error de compilación, no uno de runtime.
## ProvideFn [#providefn]
**Propósito:** la forma de función que se pasa a [`app.provide()`](./arcton-app.mdx#provide).
**Firma**
```ts
import type { Context, QueryParams, RouteParams } from '@arcton/contracts'
type ProvideFn> = (
ctx: Context
) => R | Promise
```
**Comportamiento:** corre antes de la validación a nivel de ruta, así que solo ve los valores por defecto crudos de `params`/`query` — nunca el output del schema de una ruta. Su valor de retorno, `R`, se fusiona de forma plana sobre `ctx`. Ver [Providers](../providers/overview.mdx).
# OpenAPI (/es/docs/api/openapi)
## Resumen [#resumen]
Sirve un documento OpenAPI 3.1 y una UI de Scalar que lo lee, generados a
partir de `params`/`query`/`body`/`response`/`detail` propios de cada ruta:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.use(openapi({ info: { title: 'API', version: '1.0.0' } }))
app.listen()
```
Ver [OpenAPI & Scalar](../integrations/openapi.mdx) para la guía orientada
al uso.
## `openapi()` [#openapi]
**Propósito** — construye el middleware que sirve el documento y la página
de Scalar. Se registra con `app.use()`.
**Firma**
```ts no-check
import type { RouteAwareMiddleware } from '@arcton/contracts'
function openapi(options: OpenAPIOptions): RouteAwareMiddleware
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | ---------------- | ------------------------------------------------------ |
| `options` | `OpenAPIOptions` | Requerido — como mínimo, `info`. Ver abajo cada campo. |
**Tipo de retorno** — un [`RouteAwareMiddleware`](#routeawaremiddleware).
**Comportamiento** — responde los requests `GET` al documento
(`document.path`, por defecto `/openapi.json`) y, salvo que se pase
`docs: false`, a una página de Scalar (`docs.path`, por defecto `/docs`) que
carga el documento por URL en vez de embeber una segunda copia. Todo otro
request sigue a `next()`. El documento se construye una sola vez, en el
primer request que lo pide — con todos los modules ya montados — y nunca por
request. Corre en orden de registro como cualquier middleware, así que uno
registrado después de un middleware de autenticación queda protegido por él.
**Errores** — no hay error de registro: una ruta en alguno de los mismos
paths queda tapada si `openapi()` se registró antes que ella, y responde con
normalidad si se registró después. Usar `openapi()` en cualquier lugar que no
sea `app.use()` (el middleware propio de una ruta, por ejemplo) lanza
`openapi() must be registered with app.use()` en el primer request al
documento.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
import * as z from 'zod'
const app = Arcton()
app.get('/users/:id', {
params: z.object({ id: z.uuid() }),
response: z.object({ id: z.string() }),
detail: { operationId: 'getUser', tags: ['Users'] },
handler: ctx => ({ id: ctx.params.id })
})
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
docs: { path: '/reference' }
})
)
app.listen({ port: 3000 })
```
## `OpenAPIOptions` [#openapioptions]
**Propósito** — el objeto de opciones que acepta `openapi()`.
**Firma**
```ts no-check
interface OpenAPIOptions extends DocumentOptions {
document?: { path?: string }
docs?: (ScalarOptions & { path?: string }) | false
}
```
**Campos**
| Campo | Tipo | Default | Descripción |
| --------------- | ------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `info` | `OpenAPIInfo` | — | Requerido — ver [`DocumentOptions`](#documentoptions). |
| `servers` | `object[]` | — | Ver [`DocumentOptions`](#documentoptions). |
| `tags` | `object[]` | — | Ver [`DocumentOptions`](#documentoptions). |
| `security` | `object[]` | — | Ver [`DocumentOptions`](#documentoptions). |
| `document.path` | `string` | `'/openapi.json'` | Dónde se sirve el documento en sí. |
| `docs` | `ScalarOptions \| false` | `{}` | Las opciones propias de Scalar — ver [`ScalarOptions`](#scalaroptions) — más `path` (default `'/docs'`). `false` sirve solo el documento, sin UI. |
**Comportamiento** — `document` y `docs` se mantienen separados de
`info`/`servers`/`tags`/`security` a propósito: un lado describe la API, el
otro describe la UI que la lee. Ver [Configurar los
paths](../integrations/openapi.mdx#configuring-the-paths) y [Configurar
Scalar](../integrations/openapi.mdx#configuring-scalar).
## `OpenAPIInfo` [#openapiinfo]
**Propósito** — el objeto `info` del documento — el único campo requerido
de `OpenAPIOptions`.
**Firma**
```ts
interface OpenAPIInfo {
title: string
version: string
description?: string
[key: string]: unknown
}
```
**Campos**
| Campo | Tipo | Descripción |
| ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `title` | `string` | El nombre de la API. |
| `version` | `string` | La versión propia de la API — no está relacionada con la versión del spec de OpenAPI (`3.1.0`, siempre asignada automáticamente). |
| `description` | `string` | Opcional. |
**Comportamiento** — cualquier otro campo de `info` de OpenAPI
(`termsOfService`, `contact`, `license`, ...) se acepta a través del index
signature y se pasa directo al documento, sin validar.
## `DocumentOptions` [#documentoptions]
**Propósito** — los campos a nivel de documento que extiende
`OpenAPIOptions`; también lo que recibe [`buildDocument()`](#builddocument)
por sí mismo.
**Firma**
```ts no-check
interface DocumentOptions {
info: OpenAPIInfo
servers?: Record[]
tags?: Record[]
security?: Record[]
}
```
**Campos**
| Campo | Tipo | Descripción |
| ---------- | ------------- | ----------------------------------------------------------------- |
| `info` | `OpenAPIInfo` | Ver [`OpenAPIInfo`](#openapiinfo). |
| `servers` | `object[]` | Server Objects de OpenAPI, pasados tal cual se dan. |
| `tags` | `object[]` | Tag Objects de OpenAPI, pasados tal cual se dan. |
| `security` | `object[]` | Security Requirement Objects de OpenAPI, pasados tal cual se dan. |
**Comportamiento** — `servers`/`tags`/`security` se copian al documento tal
cual cuando están presentes, y se omiten por completo en caso contrario —
ninguno de los tres tiene un valor por defecto.
## `ScalarOptions` [#scalaroptions]
**Propósito** — la configuración propia de Scalar, bajo
`OpenAPIOptions.docs`.
**Firma**
```ts
interface ScalarOptions {
pageTitle?: string
cdn?: string
configuration?: Record
}
```
**Campos**
| Campo | Tipo | Default | Descripción |
| --------------- | -------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pageTitle` | `string` | `'Scalar API Reference'` | El `` de la página `/docs`. |
| `cdn` | `string` | jsDelivr | Desde dónde se carga el bundle de JS de Scalar — asígnalo para apuntar a un build self-hosted. |
| `configuration` | `object` | `{}` | El objeto de configuración propio de Scalar (theme, sidebar, auth, ...) — ver la [documentación de configuración de Scalar](https://guides.scalar.com/scalar/scalar-api-references/configuration). |
**Comportamiento** — `configuration.url` siempre se asigna automáticamente,
a partir de `OpenAPIOptions.document.path` — la página lee el documento por
URL, así que nunca embebe una segunda copia. Cualquier `url` pasado en
`configuration` se sobrescribe.
## `buildDocument()` [#builddocument]
**Propósito** — la función de más bajo nivel que `openapi()` llama
internamente: convierte un conjunto de route records directamente en un
objeto de documento OpenAPI, sin integración HTTP. Útil para escribir el
documento a un archivo en build time, o para testear qué produce un
conjunto de rutas sin levantar un servidor.
**Firma**
```ts no-check
import type { RouteRecord } from '@arcton/contracts'
function buildDocument(
records: readonly RouteRecord[],
options: DocumentOptions
): Record
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | ------------------------ | ------------------------------------------------------------------------- |
| `records` | `readonly RouteRecord[]` | Típicamente el resultado de [`routesOf(app)`](./arcton-app.mdx#routesof). |
| `options` | `DocumentOptions` | Ver [`DocumentOptions`](#documentoptions) arriba. |
**Tipo de retorno** — un documento OpenAPI 3.1 plano, serializable a JSON.
**Ejemplo**
```ts
import { Arcton, routesOf } from '@arcton/core'
import { buildDocument } from '@arcton/openapi'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
const document = buildDocument(routesOf(app), {
info: { title: 'Users API', version: '1.0.0' }
})
await Bun.write('openapi.json', JSON.stringify(document, null, 2))
```
## `RouteRecord` [#routerecord]
**Propósito** — lo que declaró una ruta, guardado junto al árbol de rutas
para que sobreviva después del registro — el árbol en sí solo guarda
handlers ya compuestos. Se lee a través de
[`routesOf(app)`](./arcton-app.mdx#routesof); es también lo que recibe el
lo que lee un [`RouteAwareMiddleware`](#routeawaremiddleware).
**Firma**
```ts no-check
import type { StandardSchemaV1 } from '@arcton/contracts'
interface RouteRecord {
method: HttpMethod
path: string
params?: StandardSchemaV1
query?: StandardSchemaV1
body?: StandardSchemaV1
bodyContent?: Record
bodyOptional?: boolean
response?: Record
detail?: RouteDetail
}
```
**Campos**
| Campo | Tipo | Descripción |
| ----------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `method` | `HttpMethod` | Un método concreto — `app.all()` produce un record por cada método que registra, nunca un record de "cualquier método". |
| `path` | `string` | El path final de la ruta, con todo prefijo de montaje ya aplicado. |
| `params`/`query`/`body` | `StandardSchemaV1` | Las instancias de schema originales, no una forma convertida — ver [`StandardSchemaV1`](./validation-types.mdx#standardschemav1). |
| `bodyContent` | `Record` | Se define en lugar de `body` cuando la ruta lista los media types que acepta (keys en minúsculas, sin parámetros). Cada uno pasa a ser una entrada de `requestBody.content`. |
| `bodyOptional` | `boolean` | `true` cuando la ruta acepta una request sin body — su `requestBody` se documenta sin `required`. |
| `response` | `Record` | Normalizado desde `RouteOptions.response` — siempre indexado por status, incluso cuando se dio un schema suelto. |
| `detail` | `RouteDetail` | Ver [`RouteDetail`](./arcton-app.mdx#routedetail). |
**Comportamiento** — una ruta `ws()` no produce ningún record, al no tener
contrato que describir. Ver [`routesOf()`](./arcton-app.mdx#routesof) para
cómo se componen los records entre modules montados.
## `RouteAwareMiddleware` [#routeawaremiddleware]
**Propósito** — un `Middleware` que documenta o inspecciona la app en la que
se registra. `openapi()` devuelve uno.
**Firma**
```ts no-check
interface RouteAwareMiddleware extends Middleware {
bindRoutes(routes: () => readonly RouteRecord[]): void
}
```
**Comportamiento** — cuando se pasa a `use()` (con scope o sin él), la app
llama a `bindRoutes` una sola vez con un lector de su propio
`RouteRecord[]`. El lector es vivo, así que llamarlo en tiempo de request ve
todo module montado hasta ese momento; `@arcton/core` nunca necesita saber
qué paquete hay del otro lado.
# Tipos de Runtime (/es/docs/api/runtime-types)
## Resumen [#resumen]
Estos tipos definen qué es un `RuntimeAdapter` y qué devuelve — son el contrato que implementan `bunAdapter` y `nodeAdapter` (ver [Adapters](./adapters.mdx)), y las formas que necesitarías si escribieras el tuyo propio. La mayoría de las aplicaciones nunca tocan esto directamente; importa cuando pasas `adapter` a `app.listen()` o cuando escribes uno nuevo.
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello from Node')
app.listen({ adapter: nodeAdapter })
```
## `RuntimeAdapter` [#runtimeadapter]
**Propósito** — la interfaz que implementa una integración de runtime para que `@arcton/core` pueda servir requests sin importar APIs de Bun o Node por sí mismo.
**Firma**
```ts no-check
interface RuntimeAdapter {
readonly name: string
readonly version: string
readonly capabilities: RuntimeCapabilities
serve(options: RuntimeServeOptions): RuntimeServer
}
```
**Comportamiento** — `name` y `version` identifican el runtime (usados en el banner de arranque impreso por `listen()`, ver [listen()](./listen.mdx)). `capabilities.websocket` se verifica una sola vez, dentro de `listen()`, contra las rutas `ws()` que existan en ese momento (incluyendo las agregadas al montar un módulo) — no en el momento de registro de `ws()`.
**Ejemplo** — ver [Adapters](./adapters.mdx) para los dos valores concretos ya incluidos.
## `RuntimeCapabilities` [#runtimecapabilities]
**Propósito** — declara qué soporta un adapter.
**Firma**
```ts
interface RuntimeCapabilities {
readonly websocket: boolean
}
```
**Comportamiento** — ambos adapters incluidos fijan `websocket: true`. Si `websocket` es `false` en el adapter pasado a `listen()` y la app tiene rutas `ws()` registradas, `listen()` lanza un error.
## `RuntimeHandler` [#runtimehandler]
**Propósito** — la forma de función del handler de requests HTTP que recibe el `serve()` de un adapter.
**Firma**
```ts no-check
type RuntimeHandler = (
request: Request,
context: RuntimeRequestContext
) => Response | undefined | Promise
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `request` | `Request` | El request entrante. Una request que no trae body debe tener `request.body === null`, no un stream vacío — así distingue una ruta con [body opcional](../validation/body.mdx#optional-bodies) ambos casos. |
| `context` | `RuntimeRequestContext` | Utilidades provistas por el runtime, hoy solo el primitivo de bajo nivel para el upgrade de WebSocket. |
**Tipo de retorno** — una `Response`, o `undefined` cuando el handler ya completó el request de otra forma (por ejemplo, un upgrade de WebSocket exitoso).
## `RuntimeServeOptions` [#runtimeserveoptions]
**Propósito** — lo que se pasa a `RuntimeAdapter.serve()`.
**Firma**
```ts no-check
interface RuntimeServeOptions {
fetch: RuntimeHandler
port: number
hostname?: string
websocket?: RuntimeWebSocketRoute[]
}
```
**Comportamiento** — `websocket` lista cada ruta `ws()` registrada en la app (incluyendo las injertadas al montar un módulo); se espera que el adapter haga auto-upgrade de los requests que coincidan con alguna de estas rutas, antes incluso de llamar a `fetch`.
## `RuntimeRequestContext` [#runtimerequestcontext]
**Propósito** — el primitivo de bajo nivel para upgrade de WebSocket que se entrega a un `RuntimeHandler`, para upgrades que no pueden expresarse como una entrada estática de `websocket` (por ejemplo, uno condicionado a autenticación).
**Firma**
```ts no-check
interface RuntimeRequestContext {
upgrade(request: Request, options?: RuntimeUpgradeOptions): boolean
}
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | ----------------------- | ------------------------------------------- |
| `request` | `Request` | El request a hacer upgrade. |
| `options` | `RuntimeUpgradeOptions` | Payload/headers opcionales para el upgrade. |
**Tipo de retorno** — `boolean`: `true` si el upgrade tuvo éxito, `false` en caso contrario.
**Comportamiento** — solo utilizable cuando `RuntimeAdapter.capabilities.websocket` es `true`. Si tiene éxito, el handler no debe además retornar una `Response`; si falla (`false`), el handler debe retornar él mismo una `Response` de error.
**Ejemplo** — un fragmento que muestra el primitivo, no un adapter completo:
```ts
import type { RuntimeHandler } from '@arcton/contracts'
const fetchFallback: RuntimeHandler = (request, context) => {
if (new URL(request.url).pathname === '/socket') {
return context.upgrade(request)
? undefined
: new Response('Upgrade failed', { status: 400 })
}
return new Response('not found', { status: 404 })
}
```
## `RuntimeUpgradeOptions` [#runtimeupgradeoptions]
**Propósito** — datos opcionales pasados junto a una llamada a `RuntimeRequestContext.upgrade()`.
**Firma**
```ts
interface RuntimeUpgradeOptions {
data?: unknown
headers?: Record
}
```
**Comportamiento** — `data` se convierte en el `RuntimeWebSocket.data` del WebSocket una vez que la conexión está abierta.
## `RuntimeWebSocket` [#runtimewebsocket]
**Propósito** — el handle de WebSocket pasado a los callbacks de un `RuntimeWebSocketHandler`.
**Firma**
```ts
interface RuntimeWebSocket {
readonly data: unknown
send(message: string | ArrayBuffer | ArrayBufferView): void
close(code?: number, reason?: string): void
}
```
**Comportamiento** — `data` lleva cualquier payload que haya producido el upgrade; es `undefined` a menos que algo haya adjuntado uno explícitamente (ver `RuntimeUpgradeOptions`).
## `RuntimeWebSocketHandler` [#runtimewebsockethandler]
**Propósito** — los callbacks para una ruta `ws()` registrada.
**Firma**
```ts no-check
interface RuntimeWebSocketHandler {
message(ws: RuntimeWebSocket, message: string | ArrayBuffer): void | Promise
open?(ws: RuntimeWebSocket): void | Promise
close?(ws: RuntimeWebSocket, code: number, reason: string): void | Promise
drain?(ws: RuntimeWebSocket): void | Promise
}
```
**Comportamiento** — solo `message` es obligatorio. Ver [WebSockets](../routing/websockets.mdx) para `app.ws()` en sí y ejemplos completos.
**Ejemplo** — un fragmento que muestra la forma:
```ts
import type { RuntimeWebSocketHandler } from '@arcton/contracts'
const echoHandler: RuntimeWebSocketHandler = {
message(ws, message) {
if (message === 'bye') {
ws.close(1000, 'client said bye')
return
}
ws.send(message)
}
}
```
## `RuntimeWebSocketRoute` [#runtimewebsocketroute]
**Propósito** — una entrada de `RuntimeServeOptions.websocket`.
**Firma**
```ts no-check
interface RuntimeWebSocketRoute {
path: string
handler: RuntimeWebSocketHandler
}
```
## `RuntimeServer` [#runtimeserver]
**Propósito** — lo que retorna `RuntimeAdapter.serve()`, y lo que `app.listen()` le devuelve a quien lo llama.
**Firma**
```ts
interface RuntimeServer {
readonly port: number
readonly url: URL
stop(closeActiveConnections?: boolean): void | Promise
}
```
**Comportamiento** — `stop()` retorna `void` en el adapter de Bun y una `Promise` en el de Node (ver [Adapters](./adapters.mdx)); hacerle `await` funciona en ambos casos. El uso completo — incluyendo `port: 0` para elegir un puerto libre — está cubierto en [listen()](./listen.mdx).
# Tipos de Validación (/es/docs/api/validation-types)
## Resumen [#resumen]
Dos contratos a nivel de tipos hacen que la validación de requests y el parsing de body personalizado funcionen sin que Arcton dependa de una librería de schemas o parsing específica: `StandardSchemaV1`, la interfaz que deben implementar los schemas de `params`/`query`/`body`, y `BodyParser`, la forma de función que debe implementar un parser personalizado registrado con `app.parser()`. Ver [Application](./arcton-app.mdx) para dónde se consumen ambos.
## `StandardSchemaV1` [#standardschemav1]
**Propósito** — una interfaz de schema neutral respecto al vendor ([standardschema.dev](https://standardschema.dev/)) implementada por Zod 3.24+, Valibot, ArkType, y otras. Cualquier schema que la implemente puede pasarse como `params`, `query`, o `body` en la forma de llamada con route-options.
**Firma**
```ts
interface StandardSchemaV1 {
readonly '~standard': StandardSchemaV1.Props
}
namespace StandardSchemaV1 {
export interface Props {
readonly version: 1
readonly vendor: string
readonly validate: (
value: unknown
) => Result | Promise>
readonly types?: Types | undefined
}
export interface Types {
readonly input: Input
readonly output: Output
}
export type Result = SuccessResult | FailureResult
export interface SuccessResult {
readonly value: Output
readonly issues?: undefined
}
export interface FailureResult {
readonly issues: ReadonlyArray
}
export interface Issue {
readonly message: string
readonly path?: ReadonlyArray | undefined
}
export interface PathSegment {
readonly key: PropertyKey
}
export type InferOutput = NonNullable<
Schema['~standard']['types']
>['output']
}
```
**Comportamiento** — `validate()` retorna un `SuccessResult` (`{ value }`) o un `FailureResult` (`{ issues }`), de forma síncrona o vía una `Promise`. `types` es un campo phantom: nunca se popula en runtime, solo se lee a través de `StandardSchemaV1.InferOutput` para que TypeScript pueda inferir el tipo de salida validado sin costo alguno en runtime. Cuando una ruta declara un schema, su `InferOutput` — no el input previo a la validación — es con lo que se tipan y completan `ctx.params`, `ctx.query`, o `ctx.body`; ver [Context](./context.mdx).
**Errores** — ninguno propio. Que `validate()` de un schema retorne `{ issues }` corta la cadena del request con una respuesta `400`; el array de issues se pasa directo al cliente.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
body: v.object({
item: v.pipe(v.string(), v.minLength(1)),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
handler: ctx => ({
userId: ctx.params.id,
order: ctx.body
})
})
app.listen()
```
Este fragmento muestra la interfaz directamente, sin una librería de schemas, implementándola a mano:
```ts
import type { StandardSchemaV1 } from '@arcton/contracts'
function positiveNumber(): StandardSchemaV1 {
return {
'~standard': {
version: 1,
vendor: 'example',
validate(value) {
const n = Number(value)
return n > 0
? { value: n }
: { issues: [{ message: 'must be a positive number' }] }
}
}
}
}
```
## `StandardJSONSchemaV1` [#standardjsonschemav1]
**Propósito** — una interfaz hermana de `StandardSchemaV1` ([Standard JSON Schema](https://standardschema.dev/json-schema)), implementada por un schema que además puede describirse a sí mismo como JSON Schema. Nada en `@arcton/core` lee esto — existe para que un paquete construido sobre Arcton, como [`@arcton/openapi`](./openapi.mdx), pueda generar documentación a partir de los mismos schemas con los que una ruta ya valida.
**Firma**
```ts
interface StandardJSONSchemaV1 {
readonly '~standard': StandardJSONSchemaV1.Props
}
namespace StandardJSONSchemaV1 {
export interface Props {
readonly jsonSchema: Converter
}
export interface Converter {
readonly input: (options: Options) => Record
readonly output: (options: Options) => Record
}
export type Target =
| 'draft-2020-12'
| 'draft-07'
| 'openapi-3.0'
| ({} & string)
export interface Options {
readonly target: Target
readonly libraryOptions?: Record | undefined
}
}
```
**Comportamiento** — comparte la misma key `'~standard'` que `StandardSchemaV1`, así que un schema que lo soporta se detecta por feature (`'jsonSchema' in schema['~standard']`), no por qué librería lo produjo. `input` y `output` son conversiones separadas porque pueden diferir — un schema con un transform acepta una forma y produce otra. Cualquiera de las dos puede lanzar cuando un schema no tiene representación en JSON Schema en absoluto (un `Date` crudo, por ejemplo); quien quiera documentación en vez de un error debe capturarlo él mismo. Zod 4.6+ y ArkType 2.2+ la implementan de forma nativa; Valibot todavía no — envuelve un schema con `toStandardJsonSchema()` de `@valibot/to-json-schema` para sumarse. Ver [OpenAPI & Scalar](../integrations/openapi.mdx#schema-requirements).
**Ejemplo**
Este fragmento muestra la interfaz directamente, sin una librería de schemas, implementándola a mano:
```ts
import type { StandardJSONSchemaV1 } from '@arcton/contracts'
function jsonString(): StandardJSONSchemaV1 {
return {
'~standard': {
jsonSchema: {
input: () => ({ type: 'string' }),
output: () => ({ type: 'string' })
}
}
}
}
```
## `BodyParser` [#bodyparser]
**Propósito** — la forma de función registrada con `app.parser(mediaType, parser)` para parsear el body de un request para un media type, sobrescribiendo o extendiendo los parsers built-in. Ver [Application](./arcton-app.mdx) para `parser()` en sí.
**Firma**
```ts
type BodyParser = (request: Request) => unknown | Promise
```
**Parámetros**
| Parámetro | Tipo | Descripción |
| --------- | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `request` | `Request` | El request entrante crudo — no `ctx`, ya que el parsing ocurre antes de que los params/query de un context sean relevantes. |
**Tipo de retorno** — `unknown | Promise`: el valor que deba convertirse en el input de validación del schema para la opción `body` de esa ruta.
**Comportamiento** — retornar `undefined` significa "no manejo esto", así que el runtime sigue buscando (y en última instancia responde `415` si nada más lo maneja). Cualquier otro valor cuenta como manejado, incluyendo `false`, `0`, y `''`. Un parser solo se consulta para una ruta que declare un schema `body` y liste el media type en `content`.
**Errores** — un parser que lanza (throw) se propaga como cualquier otro código de usuario (ver [Uncaught errors](../errors/uncaught-errors.mdx)); no se captura ni se convierte en un `400`.
**Ejemplo**
```ts
import { Arcton } from '@arcton/core'
import type { BodyParser } from '@arcton/contracts'
import * as v from 'valibot'
const csvParser: BodyParser = async request => {
const text = await request.text()
const [header = '', ...rows] = text.trim().split('\n')
const keys = header.split(',')
return rows.map(row =>
Object.fromEntries(keys.map((key, i) => [key, row.split(',')[i]]))
)
}
const app = Arcton()
app.parser('text/csv', csvParser)
app.post('/import', {
body: {
content: { 'text/csv': v.array(v.record(v.string(), v.string())) }
},
handler: ctx => ({ imported: ctx.body.length, rows: ctx.body })
})
app.listen()
```
Ver [Body parsers](../validation/body-parsers.mdx) para la tabla de parsers built-in y cómo el schema `body` de una ruta selecciona uno.
# Global Error Handler (/es/docs/errors/global-error-handler)
Los [errores no capturados](./uncaught-errors.mdx) llegan al adapter del
runtime como un `500` genérico, a menos que algo los capture antes.
`app.onError()` registra un único handler que captura cualquiera de esos
errores — de un provider, un middleware, un parser de body o el propio
handler de la ruta — antes de que lleguen tan lejos:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/risky', () => {
throw new Error('boom')
})
app.onError((err, ctx) => {
console.error(err)
return { error: 'Something went wrong' }
})
app.listen()
```
Un request a `/risky` ahora responde con lo que devuelve el handler en lugar
del texto genérico del `500` del adapter. `onError()` es opt-in — una app
que nunca lo llama sigue comportándose exactamente como describen los
[errores no capturados](./uncaught-errors.mdx).
## El status por defecto es 500 [#el-status-por-defecto-es-500]
Si el handler no asigna `ctx.response.status` por su cuenta, la respuesta
usa `500` por defecto. Asígnalo explícitamente para responder con otra
cosa — por ejemplo, distinguiendo `HttpError` para reutilizar el status que
ya trae:
```ts
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.onError((err, ctx) => {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
return { code: 'INTERNAL_SERVER_ERROR', message: 'Internal Server Error' }
})
app.listen()
```
Un status ya asignado antes del throw — por ejemplo, por un middleware que
corrió antes — se conserva si el handler nunca toca
`ctx.response.status`; el valor por defecto de `500` solo se aplica cuando
nada asignó un status en absoluto.
Como cualquier handler, `onError()` puede devolver un valor plano (mapeado
con las mismas reglas de [Response](../fundamentals/response.mdx)) o un
objeto `Response` directamente, que se envía sin cambios.
## Los errores de validación también pasan por acá [#los-errores-de-validación-también-pasan-por-acá]
Un esquema de `params`, `query` o `body` que falla — o un body que Arcton no
puede interpretar en absoluto — llega a `onError()` como un `ValidationError`:
una subclase de `HttpError` cuyos `issues` son exactamente los que devolvió la
librería de esquemas. Un `Content-Type` de body no soportado llega como un
`HttpError` con status `415`.
```ts
import { Arcton, ValidationError } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({ email: v.pipe(v.string(), v.email()) }),
handler: ctx => ({ created: ctx.body })
})
app.onError((err, ctx) => {
if (err instanceof ValidationError) {
return { error: 'Invalid request', issues: err.issues }
}
return { error: 'Something went wrong' }
})
app.listen()
```
La respuesta de arriba es un `400` aunque el handler nunca asignó un status:
para estos dos errores de request el status por defecto es el suyo propio
(`400`, `415`) en lugar de `500`.
Los errores de validación se responden justo donde ocurren, así que el
middleware que envuelve la ruta — CORS, logging de requests — sigue viendo una
respuesta normal después de `await next()`. Cualquier otro error lanzado
atraviesa primero ese middleware.
## Devolver nada declina el error [#devolver-nada-declina-el-error]
`onError()` maneja un error devolviendo un valor o una `Response`. Si no
devuelve nada, se aplica en su lugar el comportamiento por defecto de Arcton:
un error de validación responde `400` con el [body de issues](../validation/validation-errors.mdx),
un `Content-Type` no soportado responde un `415` vacío, y cualquier otro error
se propaga al adapter exactamente como con ningún handler registrado. Eso
hace de `onError()` un buen lugar para loguear todo y quedarte solo con las
respuestas que te interesan.
## También corre para el fallback de 404/405 [#también-corre-para-el-fallback-de-404405]
El [middleware](../middleware/global.mdx) global corre incluso cuando nada
matchea el request, así que `onError()` también cubre un throw ahí:
```ts
import { Arcton } from '@arcton/core'
declare function logRequest(request: Request): void
const app = Arcton()
app.use(async (ctx, next) => {
logRequest(ctx.request) // lanza un error si el logger está caído
await next()
})
app.onError((err, ctx) => ({ error: 'Something went wrong' }))
app.listen()
```
## Es un único handler, a nivel de la app completa [#es-un-único-handler-a-nivel-de-la-app-completa]
Solo existe un handler de `onError()` por app — registrar uno nuevo
reemplaza al anterior — y solo se consulta el de la instancia cuyo propio
`listen()` termina sirviendo el request. Si construyes parte de tu app como
un módulo separado y lo montas con `app.use(módulo)`, un `onError()`
registrado en ese módulo no tiene ningún efecto; los módulos componen
rutas, middleware y providers dentro de la app que los monta, no un límite
de errores independiente.
Para un límite acotado a una sola sección de la app, envuelve `next()` en un
try/catch dentro de un [middleware con scope](../middleware/scoped.mdx) — ver
[Capturar un error lanzado dentro de un middleware](./responding-with-errors.mdx#catch-a-thrown-error-inside-middleware).
Los dos se combinan bien: un try/catch con scope maneja lo que reconoce y
relanza el resto, que entonces llega a `onError()` como el catch-all final.
Si el propio handler de `onError()` lanza un error, ese error no vuelve a
pasarle por su cuenta — se propaga de la misma forma en que lo haría un
error no capturado sin ningún handler registrado.
# Errores (/es/docs/errors/overview)
## Toda respuesta pasa por el mismo mapeo [#toda-respuesta-pasa-por-el-mismo-mapeo]
Arcton no tiene un canal separado para las respuestas de error. Un handler que
encuentra un problema responde exactamente igual que uno que tiene éxito:
devolviendo un `Response`, devolviendo un valor plano que se mapea a uno, o
configurando `ctx.response` antes de que el body finalice.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => {
if (ctx.params.id === '0') {
return new Response('Not found', { status: 404 })
}
return { id: ctx.params.id }
})
app.listen()
```
Esa misma idea cubre tres situaciones que pueden surgir:
* **Algo que el cliente hizo mal** — un header faltante, un id inválido, un
body de request que falla la validación. Se responde con un `Response` 4xx
(manualmente, mediante la propia validación de Arcton, o lanzando uno de
los `HttpError` ya armados de `@arcton/core`, ver
[HTTP errors](../api/http-errors.mdx)). Ver
[Respondiendo con errores](./responding-with-errors.mdx).
* **Algo que no se manejó** — una excepción lanzada en un handler, un
provider, o un body parser personalizado. Ver
[Errores no capturados](./uncaught-errors.mdx).
* **Algo mal en cómo se registró una ruta o un middleware** — una ruta
duplicada, un nombre de parámetro inválido, un scope no estático. Estos
fallan de inmediato, al arrancar, antes de que llegue cualquier request. Ver
[Errores de registro](./registration-errors.mdx).
# Errores de Registro (/es/docs/errors/registration-errors)
## Se verifica una sola vez, en el momento de registro [#se-verifica-una-sola-vez-en-el-momento-de-registro]
Construir el árbol de rutas ocurre una sola vez, cuando el módulo carga —
al llamar a `.get()`/`.post()`/etc., `.use()`, `.ws()`, o al propio
`Arcton({ prefix })`. Arcton valida cada una de estas llamadas de inmediato
y lanza una excepción de forma síncrona si algo está mal, así un error
falla rápido al arrancar en lugar de convertirse en un match confuso en
tiempo de request.
## Ruta duplicada [#ruta-duplicada]
Registrar el mismo método y path dos veces lanza:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/x', () => 'first')
app.get('/x', () => 'second')
app.listen()
```
```
Duplicate route: GET /x is already registered
```
Esto también ocurre cuando montar un módulo produce un duplicado — ver
[Módulos](../routing/modules.mdx).
## Nombre de parámetro en conflicto [#nombre-de-parámetro-en-conflicto]
Dos nombres de parámetro distintos no pueden ocupar la misma posición en el
árbol de rutas:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ctx.params.id)
app.get('/users/:userId', ctx => ctx.params.userId)
app.listen()
```
```
Conflicting parameter name: "userId" conflicts with "id" at same position
```
Un segmento dinámico y uno wildcard en la misma posición no entran en
conflicto entre sí — solo lo hacen dos segmentos dinámicos, o dos wildcard,
con nombres distintos. Ver [Precedencia](../routing/precedence.mdx).
## Nombre de parámetro inválido [#nombre-de-parámetro-inválido]
Un nombre `:param` o `*wildcard` debe empezar con una letra y contener solo
letras, dígitos o `_`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:1id', ctx => ctx.params)
app.listen()
```
```
Invalid dynamic parameter name ":1id" in route "/users/:1id": must start with a letter and contain only letters, digits or "_"
```
La misma verificación, con "wildcard" en lugar de "dynamic", aplica a los
segmentos `*name`.
## Nombre de parámetro duplicado en una misma ruta [#nombre-de-parámetro-duplicado-en-una-misma-ruta]
El mismo nombre de parámetro no puede aparecer dos veces en una sola ruta:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/pair/:a/:a', ctx => ctx.params.a)
app.listen()
```
```
Duplicate parameter name "a" in route "/pair/:a/:a"
```
## Posición del segmento wildcard [#posición-del-segmento-wildcard]
Un segmento `*wildcard` debe ser el último segmento de la ruta:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/files/*path/edit', ctx => ctx.params.path)
app.listen()
```
```
Wildcard segment must be the last segment in route "/files/*path/edit"
```
## Formato del path [#formato-del-path]
Todo path de ruta debe empezar con `/` y no puede contener un segmento
vacío:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('users', () => 'nope')
app.listen()
```
```
Route path must start with "/", got "users"
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users//profile', () => 'nope')
app.listen()
```
```
Route path must not contain empty segments ("//"): "/users//profile"
```
## Prefixes y scopes estáticos [#prefixes-y-scopes-estáticos]
`ArctonConfig.prefix` y el `scope` en `use(scope, middleware)` deben ser
ambos paths estáticos — sin segmentos `:param` ni `*wildcard`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api/:version' })
app.listen()
```
```
Prefix "/api/:version" must be a static path — dynamic/wildcard segments aren't supported (e.g. app.use('/api', mw), not app.use('/api/:id', mw))
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/users/:id', async (ctx, next) => {
await next()
})
app.listen()
```
```
Scope "/users/:id" must be a static path — dynamic/wildcard segments aren't supported (e.g. app.use('/api', mw), not app.use('/api/:id', mw))
```
## use() con el argumento incorrecto [#use-con-el-argumento-incorrecto]
`use()` acepta una función de middleware, un par `(scope, middleware)`, o
una app de Arcton para montar como módulo — cualquier otra cosa lanza una
excepción:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use({} as never)
app.listen()
```
```
use() expects a middleware function, a (scope, middleware) pair, or an Arcton app to mount
```
# Respondiendo con Errores (/es/docs/errors/responding-with-errors)
## Devolver un Response y saltarse el mapeo por completo [#devolver-un-response-y-saltarse-el-mapeo-por-completo]
Devolver un objeto `Response` desde un handler lo deja pasar tal cual — sin
merge de headers, sin validación de status. Es la forma más directa de
responder a una request que no puede tener éxito:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/profile', ctx => {
const token = ctx.request.headers.get('authorization')
if (token !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
return { user: 'Alice' }
})
app.listen()
```
## Configurar ctx.response.status y devolver un valor plano [#configurar-ctxresponsestatus-y-devolver-un-valor-plano]
Para seguir devolviendo un objeto plano y dejar que Arcton lo serialice a
JSON, se configura el status en `ctx.response` antes de que el handler
retorne:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/orders', ctx => {
ctx.response.status = 201
return { created: true }
})
app.listen()
```
`ctx.response.status` solo se puede configurar antes de que el body de la
respuesta finalice — dentro del handler, o antes de `await next()` en un
middleware global o de ruta. Una vez que el body finaliza (el handler
retorna, un step corta la cadena, o una capa reemplaza el body después de
`next()`), `ctx.response` ya se convirtió en un `Response` real, cuyo
`status` no tiene setter — asignarle un valor lanza
`TypeError: Attempted to assign to readonly property.`. La mutación de
headers es distinta: `ctx.response.headers.set(...)` / `.append(...)` sigue
funcionando después de `await next()` y llega igual al cliente.
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const timing: Middleware = async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
}
const app = Arcton()
app.use(timing)
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
## Capturar un error lanzado dentro de un middleware [#capturar-un-error-lanzado-dentro-de-un-middleware]
Un middleware es una simple función async, así que envolver `await next()`
en un try/catch convierte en una respuesta normal cualquier cosa que el
resto de la cadena lance:
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const catchErrors: Middleware = async (ctx, next) => {
try {
await next()
} catch (error) {
ctx.response.status = 500
return { error: error instanceof Error ? error.message : 'Unknown error' }
}
}
const app = Arcton()
app.use(catchErrors)
app.get('/risky', () => {
throw new Error('boom')
})
app.listen()
```
Como el throw ocurre antes de que el valor de retorno del propio handler
finalice la respuesta, `ctx.response.status` todavía se puede escribir
cuando se ejecuta el bloque `catch`.
Para un único catch-all en lugar de un try/catch en cada middleware, ver
[Global error handler](./global-error-handler.mdx).
## Lanzar un HttpError ya armado en lugar de construirlo a mano [#lanzar-un-httperror-ya-armado-en-lugar-de-construirlo-a-mano]
Repetir `ctx.response.status = ...; return {...}` en cada lugar donde una
request puede fallar se acumula rápido. `@arcton/core` exporta `HttpError`
más un namespace `Http` con una factory por cada status común —
`Http.BadRequest`, `Http.Unauthorized`, `Http.Forbidden`, `Http.NotFound`,
`Http.MethodNotAllowed`, `Http.Conflict`, `Http.Gone`,
`Http.UnprocessableEntity`, `Http.TooManyRequests`,
`Http.InternalServerError`, `Http.ServiceUnavailable` — así el par
status/mensaje vive en un solo lugar en vez de en cada punto donde se
lanza:
```ts
import { Arcton, Http } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.listen()
```
Cada factory es una función simple, no una clase — se llama, no se
instancia con `new`. Retorna un `HttpError` (una subclase de `Error`) que
lleva:
* `status` — el status HTTP (`404` para `Http.NotFound`)
* `code` — una etiqueta estable y legible por máquina (`'NOT_FOUND'`), segura
para que un cliente haga switch sobre ella, a diferencia de `message`
* `message` — la frase de razón del status por default, sobreescribible como
primer argumento de la factory
* `body` — un segundo argumento opcional: el valor exacto a devolver en vez
del default `{ code, message }`
```ts
import { Http } from '@arcton/core'
throw Http.Conflict('Email already registered', { field: 'email' })
```
`throw Http.NotFound` — la referencia a la función pelada, sin `()` — lanza
la función misma, no un `HttpError`. Un bloque catch que chequea
`instanceof HttpError` no la va a reconocer, y llega al adapter como un
`500` sin diferenciar (ver [Errores no capturados](./uncaught-errors.mdx)).
Siempre hay que llamar a la factory.
Por sí solo, lanzar uno de estos sigue siendo un error no capturado.
Capturalo con el mismo patrón try/catch de arriba, chequeando
`instanceof HttpError` para que el status y el body que trae sean los que
arman la respuesta:
```ts
import type { Middleware } from '@arcton/contracts'
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const catchHttpErrors: Middleware = async (ctx, next) => {
try {
await next()
} catch (err) {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
throw err
}
}
const app = Arcton()
app.use(catchHttpErrors)
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.listen()
```
Un status sin factory con nombre también funciona — construí `HttpError`
directamente: `new HttpError(451, 'UNAVAILABLE_FOR_LEGAL_REASONS', 'Unavailable For Legal Reasons')`.
Ver [HTTP errors](../api/http-errors.mdx) para la lista completa de
factories y su status/code/message por default.
## Respuestas propias de Arcton [#respuestas-propias-de-arcton]
Algunas respuestas vienen del propio Arcton, no del código de la aplicación:
* Ninguna ruta coincide con la request → `404` con un body JSON con forma
`{"code":"NOT_FOUND","message":"Not Found"}`, armado directamente a partir
de `Http.NotFound()` — computado una sola vez, no por request, y resuelto
sin lanzar nunca (a diferencia de un `throw Http.NotFound()` hecho a mano
en un handler, no depende de que haya un catch-all registrado para
convertirse en respuesta — ver [HTTP errors](../api/http-errors.mdx)).
* Existe una ruta para el path pero no para este método → `405` con un
header `Allow` que lista los métodos que ese node sí tiene (por ejemplo,
`Allow: GET, POST`).
* Un schema de `params`, `query` o `body` rechaza la request → `400` con un
body JSON con forma `{"issues":[{"message":"...","path":[...]}]}` — ver
[Errores de validación](../validation/validation-errors.mdx).
* El `Content-Type` de la request no tiene un parser registrado para él →
`415` con body vacío — ver [Parsers de body](../validation/body-parsers.mdx).
* Un parser integrado no puede parsear el body (JSON malformado, por
ejemplo) → `400` con `{"issues":[{"message":"Invalid request body"}]}`.
Ver [Response](../fundamentals/response.mdx) para el mapeo completo entre el
valor de retorno de un handler y un `Response`.
# Errores no Capturados (/es/docs/errors/uncaught-errors)
## Un throw se convierte en un 500 [#un-throw-se-convierte-en-un-500]
El propio pipeline de Arcton — providers, middleware, validación, el
handler — nunca se traga una excepción. Si un handler, un
[provider](../providers/overview.mdx), o un body parser personalizado
registrado con `app.parser()` lanza una excepción, ese error se propaga
hasta llegar al runtime adapter que sirve la request — a menos que la app
haya registrado un [manejador global de errores](./global-error-handler.mdx),
que lo captura antes.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/risky', () => {
throw new Error('boom')
})
app.listen()
```
Una request a `/risky` aquí registra el error con `console.error` y
responde con un `500` — los dos adapters que vienen con el framework se
comportan así. Ver [Adapters](../api/adapters.mdx) para el mecanismo exacto
en Bun y Node.
## Dos errores que el propio Arcton puede lanzar en tiempo de request [#dos-errores-que-el-propio-arcton-puede-lanzar-en-tiempo-de-request]
Un par de checks propios de Arcton lanzan una excepción de forma síncrona
mientras se construye una respuesta, y quedan sin capturar de la misma
manera:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/broken', ctx => {
ctx.response.status = 999
return { ok: true }
})
app.listen()
```
Configurar un status fuera de `[200, 599]` lanza
`Invalid response status 999: must be between 200 and 599` cuando la
respuesta se materializa — el mismo resultado en 500 que cualquier otro
throw no capturado. Asignar `ctx.response.status` después de que el body ya
finalizó lanza por una razón distinta
(`TypeError: Attempted to assign to readonly property.`) — ver el callout
en [Respondiendo con errores](./responding-with-errors.mdx).
Conviene envolver las partes de la aplicación que pueden fallar
legítimamente — una llamada downstream, un parseo del que no se confía —
con los patrones de
[Respondiendo con errores](./responding-with-errors.mdx), o capturar todo en
un solo lugar con un
[manejador global de errores](./global-error-handler.mdx), en lugar de dejar
que lleguen al adapter como un 500 sin más.
# Aplicación (/es/docs/fundamentals/application)
Toda app de Arcton empieza igual — llama a `Arcton()` y obtienes un objeto sobre el que
registras rutas y comportamiento:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.listen()
```
Cada método de registro — `get`, `post`, `use`, `provide`, `parser` — devuelve la misma
app, así que las llamadas se pueden encadenar:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.use(async (ctx, next) => {
console.log(ctx.request.method, new URL(ctx.request.url).pathname)
await next()
})
.get('/health', () => ({ status: 'ok' }))
app.listen()
```
## Poniendo un prefix a una instancia [#poniendo-un-prefix-a-una-instancia]
`Arcton()` recibe un config opcional con un solo campo, `prefix`:
```ts
import { Arcton } from '@arcton/core'
const api = Arcton({ prefix: '/api' })
api.get('/status', () => ({ ok: true }))
api.listen()
```
`prefix` se aplica a cada ruta y ruta `ws` registrada directamente en esa instancia —
en este caso, `GET /api/status`. Tiene que ser una ruta estática (sin segmento
`:param` ni `*wildcard`), y `'/'` se comporta igual que omitirlo. La misma instancia
en la que configuras un prefix es también la que montas como module dentro de otra
app — ver [Modules](../routing/modules.mdx).
## La superficie de la app [#la-superficie-de-la-app]
| Member | Qué hace |
| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config` | el objeto `ArctonConfig` que le pasaste a `Arcton()` |
| `get` / `post` / `put` / `delete` / `patch` / `head` / `options` | registra una ruta para ese método HTTP — ver [Métodos HTTP](../routing/http-methods.mdx) |
| `ws` | registra una ruta de WebSocket — ver [WebSockets](../routing/websockets.mdx) |
| `use` | agrega middleware global o con scope de ruta, o monta un module — ver [Middleware](../middleware/overview.mdx) y [Modules](../routing/modules.mdx) |
| `provide` | compone valores tipados sobre `ctx` — ver [Providers](../providers/overview.mdx) |
| `parser` | registra un parser de body para un `Content-Type` — ver [Parsers de Body](../validation/body-parsers.mdx) |
| `listen` | arranca el servidor — ver [Opciones de listen](../configuration/listen-options.mdx) |
Cada método de ruta acepta un handler (con middleware opcional antes) o un objeto de
opciones con esquemas de `params` / `query` / `body` — ver
[Descripción general de validación](../validation/overview.mdx). Lo que pasa entre que
llega un request y corre un handler es el tema de
[Ciclo de vida de la request](./request-lifecycle.mdx).
# Context (/es/docs/fundamentals/context)
Todo middleware, provider y handler recibe el mismo tipo de objeto, `ctx`. Su forma
base siempre está:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => {
// ctx.request → the raw Request
// ctx.params → { id: string }, inferred from the route literal
// ctx.query → Record, built from the URL's search params
// ctx.response → { status?: number; headers: Headers } until it materializes
return { id: ctx.params.id, referer: ctx.request.headers.get('referer') }
})
app.listen()
```
* `request` es el [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) estándar — ver [Request](./request.mdx).
* `params` se tipa a partir del literal de ruta que le pasaste a `.get()` (o de un
esquema de `params`, si la ruta declaró uno) — ver
[Parámetros de ruta](../routing/path-parameters.mdx).
* `query` es `Record` por defecto (o el output de un esquema),
construido de forma perezosa la primera vez que lo lees — ver
[Parámetros de query](../routing/query-parameters.mdx).
* `response` empieza como `{ status?: number; headers: Headers }` y es lo que usas
para darle forma a una response antes de que se materialice — ver [Response](./response.mdx).
## El context crece con lo que registras [#el-context-crece-con-lo-que-registras]
`ctx.body` solo aparece en rutas que declaran un esquema de `body`, y cualquier valor
que devuelva una llamada a `provide()` se mezcla plano sobre `ctx` — sin namespace —
para todo lo que se registre después:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app
.provide(() => ({ requestId: crypto.randomUUID() }))
.post('/users', {
body: v.object({ name: v.pipe(v.string(), v.minLength(1)) }),
handler: ctx => ({
requestId: ctx.requestId,
body: ctx.body
})
})
app.listen()
```
`ctx.requestId` está disponible aquí porque la llamada a `provide()` de arriba corrió
primero; `ctx.body` está disponible porque esta ruta declaró un esquema de `body`.
Ninguno de los dos estaría en `ctx` — ni pasaría el type-check — sin eso. Ver
[Providers](../providers/overview.mdx) para cómo compone `provide()`, y
[Body](../validation/body.mdx) para `ctx.body`.
# Ciclo de vida de la request (/es/docs/fundamentals/request-lifecycle)
Toda request que atiende una app de Arcton pasa por la misma secuencia de etapas:
```text
coincidencia → pasos globales (snapshot al registrar) → validar → route middleware → handler → mapeo de response
```
Esta página recorre cada etapa a nivel conceptual y enlaza a dónde se cubre en
profundidad.
## Coincidencia [#coincidencia]
El método y el pathname entrantes se comparan contra el árbol de rutas. Una
coincidencia trae la cadena de handlers construida para esa ruta, más los params
capturados en el camino. Si no hay coincidencia, cae en un `404`; si coincide la ruta
pero no el método, cae en un `405` — ver [Descripción general de routing](../routing/overview.mdx),
[Precedencia](../routing/precedence.mdx) y [Errores](../errors/overview.mdx).
## El snapshot de pasos globales [#el-snapshot-de-pasos-globales]
Esto es lo más importante que hay que saber sobre cómo se componen middleware y
providers: **cuando se registra una ruta, esta captura las llamadas a `use()` y
`provide()` hechas hasta ese momento.** Las llamadas hechas después del registro no la
alcanzan.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/before', () => 'registered with no global steps yet')
app.use(async (ctx, next) => {
ctx.response.headers.set('X-Global', 'yes')
await next()
})
app.get('/after', () => 'registered after the middleware above')
app.listen()
```
`/before` corre sin ninguna de las llamadas `use()`/`provide()` de alrededor, porque
ninguna existía todavía cuando se registró. `/after` corre envuelta por el middleware
de arriba, porque ese middleware ya estaba registrado. Reordenar las dos llamadas a
`get()` respecto a `use()` cambia lo que corre cada ruta — el router nunca vuelve a
revisar esto después. Ver [Orden de ejecución](../middleware/execution-order.mdx) para
las reglas completas de orden, incluyendo middleware con scope y modules montados.
## Validar [#validar]
Si la ruta declaró esquemas de `params`, `query` o `body`, corren en ese orden contra
los valores actuales, reemplazando `ctx.params` / `ctx.query` / `ctx.body` con el
resultado validado (y posiblemente transformado). El primer esquema que falla detiene
la request ahí mismo. Ver [Descripción general de validación](../validation/overview.mdx).
## Route middleware [#route-middleware]
El middleware que se pasa directamente a una ruta corre al final, lo más cerca
posible del handler — después de cada step global y con scope, después de la
validación. Ver [Middleware a nivel de ruta](../middleware/route-level.mdx).
## Handler [#handler]
El handler corre con un `ctx` completamente tipado — ver [Context](./context.mdx) para
lo que hay en él a esta altura.
## Mapeo de response [#mapeo-de-response]
Lo que sea que devuelva el handler (o un step anterior que cortó la cadena) se mapea a
un `Response` HTTP, combinado con lo que ya esté definido en `ctx.response`. Ver
[Response](./response.mdx) para el mapeo completo.
# Request (/es/docs/fundamentals/request)
`ctx.request` es un [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) estándar — todo lo que te da la Fetch API está disponible directamente:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/whoami', ctx => ({
method: ctx.request.method,
userAgent: ctx.request.headers.get('user-agent'),
url: ctx.request.url
}))
app.listen()
```
## Query string y ruta [#query-string-y-ruta]
`new URL(ctx.request.url)` funciona si quieres la URL cruda, pero para el caso común
Arcton ya te da las piezas parseadas: `ctx.query` para los search params y
`ctx.params` para los segmentos de ruta — ver [Context](./context.mdx),
[Parámetros de query](../routing/query-parameters.mdx) y
[Parámetros de ruta](../routing/path-parameters.mdx).
## Leyendo el body directamente [#leyendo-el-body-directamente]
Leer `ctx.request` por tu cuenta — `.json()`, `.text()`, `.arrayBuffer()`,
`.formData()` — funciona igual que en cualquier `Request`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/echo', async ctx => {
const payload = await ctx.request.json()
return { received: payload }
})
app.listen()
```
Este es un camino separado de `ctx.body`: `ctx.body` solo existe en una ruta que
declara un esquema de `body`, y su valor es lo que salió de la validación, ya parseado
según el `Content-Type` de la request y transformado por tu esquema. Ver
[Body](../validation/body.mdx) y [Parsers de Body](../validation/body-parsers.mdx)
para ese camino.
# Response (/es/docs/fundamentals/response)
Un handler devuelve lo que sea que deba contener la response, y Arcton lo mapea a un
`Response`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/json', () => ({ ok: true }))
app.get('/text', () => 'plain text')
app.get('/bytes', () => new Uint8Array([1, 2, 3]))
app.get('/raw', () => new Response('custom', { status: 202 }))
app.listen()
```
## El mapeo completo [#el-mapeo-completo]
| Devuelto | Body | `Content-Type` inferido |
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `Response` | pasa tal cual; `ctx.response` se ignora por completo | — |
| `string` | el string | `text/plain; charset=UTF-8` |
| objeto plano o array | `JSON.stringify(...)` | `application/json; charset=UTF-8` |
| `Blob` | el blob | `blob.type`, o `application/octet-stream` cuando está vacío |
| `FormData` | el form data | ninguno — se elimina un `Content-Type` explícito para que el runtime pueda generar su propio boundary de multipart |
| `URLSearchParams` | los params | ninguno inferido (el runtime define `application/x-www-form-urlencoded;charset=UTF-8`) |
| `ArrayBuffer`, o cualquier view de uno (`Uint8Array`, `Int32Array`, `DataView`, `Buffer` de Node) | los bytes | `application/octet-stream` |
| `ReadableStream` | en streaming | `application/octet-stream` |
| `null`, `undefined`, o sin retorno | vacío | ninguno |
Un `ctx.response.headers.set('Content-Type', ...)` explícito siempre gana sobre el
inferido, con una excepción:
Devolver `FormData` descarta cualquier `Content-Type` que hayas definido tú mismo —
Arcton lo elimina para que el runtime pueda generar su propio header
`multipart/form-data; boundary=...`. Puedes definir otros headers libremente; el
boundary tiene que venir del runtime.
`Map` y `Set` no reciben un tratamiento especial — caen en la rama de objeto plano, y
`JSON.stringify` los serializa como `{}`. Devuelve en su lugar un array o un objeto
plano construido a partir de sus entradas, por ejemplo `Object.fromEntries(myMap)` o
`[...mySet]`.
## Status [#status]
`ctx.response.status` define el status; por defecto es `200`. Un status fuera de
`200`–`599` lanza `Invalid response status N: must be between 200 and 599`.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/users', ctx => {
ctx.response.status = 201
ctx.response.headers.set('Location', '/users/1')
return { id: '1' }
})
app.listen()
```
Define `ctx.response.status` antes de que la response se materialice — en el
handler, o antes de llamar a `await next()` en el middleware. Definirlo después lanza
un error, porque para ese momento ya es parte de un `Response` real, cuyo `status` no
se puede reasignar.
`204`, `205` y `304` fuerzan un body vacío: se descarta un `Content-Type` inferido,
pero un `Content-Type` que hayas definido explícitamente sobrevive.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.delete('/users/:id', ctx => {
ctx.response.status = 204
})
app.listen()
```
## Definiendo cookies [#definiendo-cookies]
`ctx.response.headers` es un objeto `Headers` real — `.append('Set-Cookie', ...)`
agrega una cookie sin pisar las que ya estén definidas, así que varias cookies
funcionan llamándolo más de una vez. Esto funciona tanto si lo haces en el handler
como en middleware después de `await next()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.append('Set-Cookie', 'theme=dark; Path=/')
ctx.response.headers.append('Set-Cookie', 'session=abc123; HttpOnly; Path=/')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
Que la mutación de headers después de `await next()` llegue al cliente de esta forma
— y que el status solo se pueda definir antes de ese punto — viene de cómo
`ctx.response` se materializa en una response real a medida que el pipeline se
desenrolla. Ver [Ciclo de vida de la request](./request-lifecycle.mdx) y
[Modificando responses](../middleware/modifying-responses.mdx) para ese mecanismo.
# Despliegue (/es/docs/getting-started/deployment)
Desplegar una app de Arcton se reduce a ejecutar un comando de build y luego arrancar
el resultado — qué comando depende de qué template hayas generado.
## Bun: compilar un binario independiente [#bun-compilar-un-binario-independiente]
El script `compile` del template de Bun empaqueta tu app y el runtime de Bun en un
único ejecutable:
```bash
bun run compile
```
que ejecuta:
```bash
bun build --compile --minify --sourcemap ./src/index.ts --outfile arcton-app
```
El resultado es un binario autocontenido — sin `node_modules`, sin necesidad de
instalar el runtime por separado en la máquina destino:
```bash
./arcton-app
```
Si prefieres ejecutar el código fuente directamente sin compilar, el script `start`
del template hace eso en su lugar:
```bash
bun run start
```
## Node.js: compilar y luego ejecutar [#nodejs-compilar-y-luego-ejecutar]
El script `build` del template de Node.js verifica los tipos y emite JavaScript:
```bash
npm run build
```
que ejecuta:
```bash
tsc --build
```
Después arranca el resultado compilado con el script `start`:
```bash
npm run start
```
que ejecuta:
```bash
node dist/index.js
```
## Etiquetando el entorno [#etiquetando-el-entorno]
Pasa `env` a `listen()` para etiquetar el banner de inicio con el entorno al que estás
desplegando — ver [Entorno](../configuration/environment.mdx).
# Desarrollo (/es/docs/getting-started/development)
Ambos templates vienen con un script `dev` conectado a su runtime, así que la forma de
arrancar el desarrollo local es la misma sin importar cuál hayas elegido:
```bash
bun run dev
```
```bash
npm run dev
```
```bash
pnpm run dev
```
## Qué ejecuta el script `dev` de cada template [#qué-ejecuta-el-script-dev-de-cada-template]
El script `dev` del template de Bun es:
```bash
bun --hot src/index.ts
```
`--hot` recarga tu código a medida que cambian los archivos sin cerrar las conexiones
abiertas, así que puedes seguir iterando sobre rutas y middleware sin reiniciar el
proceso a mano.
El script `dev` del template de Node.js es:
```bash
tsx watch src/index.ts
```
`tsx` ejecuta el entry point de TypeScript directamente, y `watch` reinicia el proceso
cada vez que cambia un archivo fuente.
## Entorno [#entorno]
La opción `env` de `listen()` solo etiqueta el banner de inicio que imprime — por
defecto usa `process.env.NODE_ENV`, y si eso no está definido cae en `'development'`,
que es justo el caso mientras corres cualquiera de los dos scripts de dev. Ver
[Entorno](../configuration/environment.mdx) para saber cómo definirlo explícitamente.
# Tu primer servidor (/es/docs/getting-started/first-server)
Una aplicación de Arcton empieza con una sola llamada a `Arcton()`. Registra una ruta
en ella y luego llama a `listen()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen()
```
Ejecútalo con `bun src/index.ts` (o `tsx src/index.ts` en Node.js) y escucha
en el puerto 3000 por defecto, imprimiendo un banner de inicio con la URL en la que está
sirviendo.
## Devolviendo datos [#devolviendo-datos]
Lo que sea que el handler devuelva se convierte en el body de la response. Devuelve un objeto
o array y se serializa como JSON automáticamente:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
El conjunto completo de tipos de retorno que Arcton entiende — strings, objetos, datos
binarios, streams, un `Response` en crudo — está en [Response](../fundamentals/response.mdx).
## Leyendo un parámetro de ruta [#leyendo-un-parámetro-de-ruta]
Un segmento `:param` en la ruta se captura y se tipa en `ctx.params`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
Ver [Parámetros de ruta](../routing/path-parameters.mdx) para saber cómo se hace match de
los segmentos, y [Aplicación](../fundamentals/application.mdx) para el resto de lo que puede
hacer una instancia de app.
## Eligiendo un puerto [#eligiendo-un-puerto]
`listen()` recibe un objeto de opciones:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ port: 4000 })
```
La lista completa de opciones está en [Opciones de listen](../configuration/listen-options.mdx).
# Instalación (/es/docs/getting-started/installation)
La forma más rápida de empezar un proyecto de Arcton es el scaffold interactivo. Elige el comando que corresponda al package manager que ya tengas:
```bash
bun create arcton
```
```bash
npm create arcton
```
```bash
pnpm create arcton
```
También puedes ejecutarlo directamente a través del CLI de `arcton`:
```bash
bunx arcton create my-arcton-app
```
Pasar un nombre (`my-arcton-app` arriba) te salta el prompt de nombre de proyecto.
## Qué pregunta el scaffold [#qué-pregunta-el-scaffold]
El CLI recorre un pequeño conjunto de prompts:
* **Nombre del proyecto** — se usa para la carpeta y para el `package.json` generado.
* **Runtime** — Bun o Node.js. Esto determina qué template se copia y si `@arcton/adapter-node` se agrega como dependencia.
* **Package manager** — bun, pnpm o npm, usado solo para elegir el comando de instalación que te ofrece ejecutar.
* **¿Instalar dependencias ahora?** — opcional; siempre puedes instalar más tarde.
Cuando termina, imprime los próximos comandos a ejecutar (`cd` al proyecto, instalar si te saltaste ese paso, y luego el script de dev).
## Próximos pasos [#próximos-pasos]
Ver [Estructura del proyecto](./project-structure.mdx) para ver qué se generó,
[Tu primer servidor](./first-server.mdx) para ver el código que ya está ahí,
y [Desarrollo](./development.mdx) para ejecutarlo.
# Estructura del proyecto (/es/docs/getting-started/project-structure)
El scaffold de [instalación](./installation.mdx) copia uno de dos templates pequeños
según el runtime que elijas. Ambos son intencionalmente mínimos — una dependencia, un
archivo de código fuente.
## Template de Bun [#template-de-bun]
```text
my-arcton-app/
├── package.json
└── src/
└── index.ts
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen()
```
`package.json` depende de `@arcton/core` y declara tres scripts —
`dev`, `start` y `compile` — cubiertos en [Desarrollo](./development.mdx) y
[Despliegue](./deployment.mdx).
## Template de Node.js [#template-de-nodejs]
```text
my-arcton-app/
├── package.json
├── tsconfig.json
└── src/
└── index.ts
```
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => {
return 'Hello, Arcton!'
})
app.listen({ adapter: nodeAdapter })
```
La única diferencia respecto al template de Bun es la dependencia extra
`@arcton/adapter-node` y la opción `adapter: nodeAdapter` que se pasa a `listen()` — ver
[Runtimes](../fundamentals/application.mdx) para entender por qué esa es la única línea
que cambia. Acá `package.json` declara `dev`, `build` y `start`, y
`tsconfig.json` configura el build de TypeScript que usa el script `build`.
## Creciendo desde aquí [#creciendo-desde-aquí]
Ambos templates son una app de Arcton normal — todo lo de
[Fundamentos](../fundamentals/application.mdx),
[Enrutamiento](../routing/overview.mdx) y más allá aplica directamente a `src/index.ts`.
# Configuración de la App (/es/docs/configuration/app-config)
## Darle un prefix a una instancia [#darle-un-prefix-a-una-instancia]
Toda instancia de `Arcton()` recibe un objeto de configuración opcional.
Tiene exactamente un campo: `prefix`.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api' })
app.get('/users', () => ({ users: [] }))
app.listen()
```
Con `prefix: '/api'`, la route de arriba queda disponible en `GET /api/users`.
El prefix se aplica a cada route y ruta `ws()` registrada directamente en esta
instancia: escribes `'/users'`, Arcton sirve `/api/users`.
## Leer la configuración de vuelta [#leer-la-configuración-de-vuelta]
`app.config` expone exactamente el mismo objeto que le pasaste a `Arcton()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton({ prefix: '/api' })
console.log(app.config.prefix) // '/api'
app.listen()
```
## Reglas para `prefix` [#reglas-para-prefix]
* `prefix` debe ser una **ruta estática** — un segmento `:param` o
`*wildcard` lanza un error al llamar a `Arcton()`. Consulta
[Errores de registro](../errors/registration-errors.mdx) para ver el
mensaje exacto.
* `'/'` y omitir `prefix` por completo son equivalentes — ambos significan
que no hay prefix.
* Cuando un module (una instancia de `Arcton()` montada con
`app.use(module)`) tiene su propio prefix, el prefix del padre y el del
module se combinan. Consulta [Modules](../routing/modules.mdx) para ver
cómo funciona esa combinación.
`prefix` solo afecta a las routes y rutas `ws()` registradas directamente
en esa instancia. No tiene nada que ver con `use(scope, middleware)` — un
scope es una comparación de ruta separada, sin prefix. Consulta
[Middleware con scope](../middleware/scoped.mdx).
# Entorno (/es/docs/configuration/environment)
## Qué hace `env` [#qué-hace-env]
`app.listen()` recibe una opción `env` que por defecto vale
`process.env.NODE_ENV ?? 'development'`. Se usa para exactamente una cosa: la
etiqueta que se imprime en el banner de inicio.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ env: 'staging' })
```
El banner imprime entonces `Environment staging` en vez del valor por
defecto. Consulta [Opciones de Listen](./listen-options.mdx) para el resto de
lo que `listen()` imprime y devuelve.
## Leer variables de entorno [#leer-variables-de-entorno]
Más allá de esa única etiqueta, las variables de entorno se leen de la forma
normal para el runtime que esté sirviendo la app — no hay ninguna capa de
configuración propia de Arcton de por medio.
En Bun, los archivos `.env` se cargan automáticamente, así que `process.env`
ya tiene lo que sea que defina un archivo `.env` para cuando corre tu código:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
const databaseUrl = process.env.DATABASE_URL
app.get('/health', () => ({ ok: databaseUrl !== undefined }))
app.listen()
```
En Node.js, lee `process.env` de la misma manera. Carga un archivo `.env`
primero si usas uno — por ejemplo con la propia flag `--env-file` de Node al
arrancar el proceso:
```bash
node --env-file=.env dist/index.js
```
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
const databaseUrl = process.env.DATABASE_URL
app.get('/health', () => ({ ok: databaseUrl !== undefined }))
app.listen({ adapter: nodeAdapter })
```
`NODE_ENV` no se lee para nada más que ese valor por defecto de `env` — si
tu propio código toma decisiones según esa variable (feature flags, nivel
de logging, etc.), lee `process.env.NODE_ENV` directamente, igual que hace
`app.listen()`.
# Opciones de Listen (/es/docs/configuration/listen-options)
## Levantar un servidor [#levantar-un-servidor]
`app.listen()` recibe un objeto de opciones opcional y devuelve un
`RuntimeServer`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ port: 8080, hostname: '0.0.0.0' })
```
Todos los campos son opcionales:
Llamar a `app.listen()` sin argumentos arranca en el puerto 3000 usando el
adapter de Bun:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen()
```
## Elegir un puerto libre [#elegir-un-puerto-libre]
Pasar `port: 0` le pide al sistema operativo un puerto libre en vez de uno
fijo. Lee el puerto real desde el servidor que te devuelve:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
const server = app.listen({ port: 0 })
console.log(server.port) // an OS-assigned port
console.log(server.url) // e.g. http://localhost:54231/
server.stop()
```
Este es exactamente el patrón que se usa para testear una app real de punta a
punta — consulta [Resumen de testing](../testing/overview.mdx).
## Elegir un adapter [#elegir-un-adapter]
`adapter` selecciona qué runtime sirve la app. El valor por defecto es
`bunAdapter`. Pasa `nodeAdapter` para correr sobre Node.js en su lugar:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ adapter: nodeAdapter })
```
Consulta [Adapters](../api/adapters.mdx) para saber qué es un adapter, y
[Soporte de runtime](../introduction/runtime-support.mdx) para las
diferencias concretas entre los dos adapters que vienen incluidos.
## El banner de inicio y el servidor devuelto [#el-banner-de-inicio-y-el-servidor-devuelto]
`listen()` imprime un banner de inicio — el wordmark de Arcton, seguido de la
versión de Arcton, el nombre y la versión del runtime, la etiqueta de
entorno y la URL en la que está escuchando. La opción `env` controla
solamente esa etiqueta; consulta [Entorno](./environment.mdx) para los
detalles.
Devuelve un `RuntimeServer`:
```ts
interface RuntimeServer {
readonly port: number
readonly url: URL
stop(closeActiveConnections?: boolean): void | Promise
}
```
`stop()` devuelve `void` en el adapter de Bun y un `Promise` en el de
Node, así que siempre es seguro esperarlo con `await`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
const server = app.listen({ port: 0 })
await server.stop()
```
Consulta [listen()](../api/listen.mdx) para la referencia completa de la
API.
## Apagado elegante [#apagado-elegante]
Por defecto, `listen()` drena el servidor al recibir `SIGTERM`/`SIGINT` en
vez de dejar la terminación en manos del comportamiento por defecto del
runtime: deja de aceptar conexiones nuevas, espera a que las requests en
curso terminen (hasta `shutdownTimeout`, 10 segundos por defecto), y luego
sale del proceso. Si una request sigue en curso una vez agotado el timeout,
las conexiones activas se cierran a la fuerza en su lugar.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'Hello, Arcton!')
app.listen({ shutdownTimeout: 5000 })
```
`gracefulShutdown` está pensado para aplicaciones donde Arcton es dueño del
ciclo de vida del proceso — al recibir la señal, llama a `process.exit()`,
que termina *todo* el proceso, no solo este servidor. Ponlo en `false`
cuando la aplicación anfitriona maneja las señales del proceso por su
cuenta (por ejemplo, Arcton incrustado dentro de un proceso más grande, o
un runtime donde las señales del sistema operativo no tienen sentido):
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.listen({ gracefulShutdown: false })
```
Una segunda `SIGTERM`/`SIGINT` recibida mientras ya se está apagando se
ignora — no inicia un segundo drenaje concurrente.
# Better Auth (/es/docs/integrations/better-auth)
[Better Auth](https://www.better-auth.com) es una librería de autenticación
independiente del framework. Expone un handler estándar de la Web — una
función que recibe un `Request` y devuelve un `Response` — junto con una
pequeña API de servidor para leer la sesión actual.
Esta guía asume que ya tienes una app de Arcton y una instancia de Better
Auth configurada. Si todavía no configuraste Better Auth, consulta su propia
[guía de instalación](https://www.better-auth.com/docs/installation). Cada
ejemplo de abajo importa esa instancia desde un módulo local `./auth` — un
reemplazo de la tuya:
```ts title="auth.ts"
declare const auth: {
handler: (request: Request) => Promise
api: {
getSession: (options: {
headers: Headers
}) => Promise<{
user: { id: string; email: string }
session: { id: string }
} | null>
}
}
export { auth }
```
## Instalación [#instalación]
```bash
bun add better-auth
```
```bash
npm install better-auth
```
```bash
pnpm add better-auth
```
```bash
yarn add better-auth
```
## Registrar el handler de Better Auth [#registrar-el-handler-de-better-auth]
El `auth.handler` de Better Auth recibe un `Request` y devuelve un
`Response`. Reenvía cada solicitud bajo tu ruta de autenticación con
[`app.all()`](../routing/http-methods.mdx#every-method-on-one-path):
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { auth } from './auth'
const app = Arcton()
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
`app.all()` registra el mismo handler para todos los métodos HTTP que
soporta Arcton, así que esta única ruta responde a `GET`, `POST` y el resto
de métodos que necesitan las rutas de Better Auth: registro, inicio de
sesión, cierre de sesión, consulta de sesión, y demás.
Un handler puede devolver un `Response` directamente, y Arcton lo envía tal
cual, así que la respuesta de `auth.handler` llega al cliente sin cambios.
Consulta [Response](../fundamentals/response.mdx) para más detalles.
`*path` es un [wildcard](../routing/path-parameters.mdx) y requiere al
menos un segmento, por lo que una solicitud a `/api/auth` sola no
coincide. Si tu aplicación necesita manejar esa ruta exacta, regístrala
aparte: `app.all('/api/auth', ctx => auth.handler(ctx.request))`.
## CORS [#cors]
Si tu frontend corre en otro origen, agrega
[`@arcton/cors`](../middleware/cors.mdx) antes de la ruta de autenticación,
con `credentials: true` para que la cookie de sesión se envíe entre
orígenes. Agrega ese mismo origen a `trustedOrigins` de Better Auth:
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
import { auth } from './auth'
const app = Arcton()
app.use(
cors({
origin: 'http://localhost:3001',
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
})
)
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
Consulta [CORS](../middleware/cors.mdx) para ver todas las opciones
disponibles.
## Acceder a la sesión en rutas protegidas [#acceder-a-la-sesión-en-rutas-protegidas]
Usa `auth.api.getSession()` para leer la sesión actual a partir de los
encabezados de la solicitud, y expón esa información con
[`provide()`](../providers/overview.mdx) para que esté disponible en `ctx`
en cualquier ruta registrada después:
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { auth } from './auth'
const app = Arcton()
.provide(async ctx => {
const session = await auth.api.getSession({ headers: ctx.request.headers })
return { user: session?.user ?? null, session: session?.session ?? null }
})
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.get(
'/me',
async (ctx, next) => {
if (!ctx.user) return new Response('Unauthorized', { status: 401 })
await next()
},
ctx => ({ user: ctx.user })
)
app.listen()
```
`ctx.user` y `ctx.session` son `null` cuando no hay una sesión activa.
Agrega un middleware como el de arriba a cualquier ruta que deba requerir
autenticación — puedes aplicarlo por ruta, o con `use()` sobre toda una
sección de rutas.
## Ejemplo completo [#ejemplo-completo]
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
import { auth } from './auth'
const app = Arcton()
.use(
cors({
origin: 'http://localhost:3001',
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
})
)
.provide(async ctx => {
const session = await auth.api.getSession({ headers: ctx.request.headers })
return { user: session?.user ?? null, session: session?.session ?? null }
})
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.get(
'/me',
async (ctx, next) => {
if (!ctx.user) return new Response('Unauthorized', { status: 401 })
await next()
},
ctx => ({ user: ctx.user })
)
app.get('/posts', ctx => ({ posts: [], viewer: ctx.user }))
app.listen()
```
Esto funciona igual en Bun y en Node — Arcton entrega a `auth.handler` un
`Request` estándar en cualquiera de los dos runtimes.
# Logging (/es/docs/integrations/logger)
`@arcton/logger` loguea una línea por request — método, path, status,
duración — sin ninguna dependencia en runtime. Es un único middleware:
ninguna configuración vive en `Arcton()` ni en `listen()`.
## Instalación [#instalación]
```bash
bun add @arcton/logger
```
```bash
npm install @arcton/logger
```
```bash
pnpm add @arcton/logger
```
```bash
yarn add @arcton/logger
```
## Uso básico [#uso-básico]
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger())
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
Cada request ahora produce una línea de JSON, una vez que se conoce la
respuesta:
```json
{"level":"info","time":"2026-09-14T16:00:00.000Z","msg":"GET /users/1 200 0.4ms","method":"GET","path":"/users/1","status":200,"durationMs":0.4}
```
## El status decide el nivel [#el-status-decide-el-nivel]
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger())
app.get('/ok', () => ({ ok: true })) // logueado a info
app.get('/missing', ctx => {
ctx.response.status = 404 // logueado a warn (4xx)
return { error: 'not found' }
})
app.get('/boom', () => {
throw new Error('kaboom') // logueado a error
})
app.listen()
```
Una respuesta `2xx`/`3xx` se loguea a `info`, una `4xx` a `warn`, una `5xx`
a `error` — ningún handler tiene que loguear nada por su cuenta. Si un
request falla y nada aguas abajo captura el error, el logger lo loguea a
`error` con el error adjunto y vuelve a lanzarlo sin modificarlo, así que
el manejo de errores (un handler de
[`onError()`](../errors/global-error-handler.mdx), o ninguno) se comporta
exactamente igual que sin el logger.
## Modo pretty [#modo-pretty]
`pretty: true` cambia JSON por un formato pensado para leerse en vivo, en
una terminal — sin dependencia que instalar, sin transport que configurar:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
app.use(logger({ pretty: process.env.NODE_ENV !== 'production' }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
Un request ahora imprime dos líneas en vez de una — `→` cuando llega, `←`
cuando termina — cada una con el mismo `level` que llevaría una línea de
JSON, escrito y coloreado, no solo implícito por el color:
```text
→ INFO 16:00:00.000 GET /users/1
← INFO 16:00:00.004 200 GET /users/1 0.4ms
```
Un request que falla sin que nada capture el error queda etiquetado
`ERROR` en vez de un status — no hay ninguno, igual que la línea de JSON
para este caso no tiene campo `status` — con el mensaje del error al
final:
```text
→ INFO 16:00:01.000 GET /boom
← ERROR 16:00:01.001 GET /boom 0.1ms kaboom
```
`level` sigue filtrando qué se imprime: `'silent'` no imprime nada, y un
nivel por encima del que tendría un request dado (un mínimo `warn`, por
ejemplo) descarta la línea `→` de llegada y cualquier línea `←`/`ERR` que
tampoco lo supere.
## Child loggers [#child-loggers]
`log.child(bindings)` devuelve un nuevo logger con `bindings` mezclado en
cada record que escriba de ahí en adelante — útil para etiquetar cada
línea de una parte de la app sin repetir esos campos en cada llamada:
```ts
import { createLogger } from '@arcton/logger'
const log = createLogger()
const dbLog = log.child({ component: 'database' })
dbLog.info('query executed', { table: 'users' })
// { "component": "database", "table": "users", "msg": "query executed", ... }
```
Los children se componen — un nieto lleva cada binding que agregaron sus
ancestros. `createLogger()` construye un
[`Logger`](../api/logger.mdx#logger) independiente, sin depender de ningún
request; consultá la [referencia de la API](../api/logger.mdx) para el
conjunto completo `trace`/`debug`/`info`/`warn`/`error`/`fatal`.
## Un sink personalizado [#un-sink-personalizado]
`sink` es dónde se escribe una línea formateada — `process.stdout.write`
por defecto (con fallback a `console.log` donde `process` no existe, como
un Worker). Pasá el tuyo propio para redirigir la salida, por ejemplo para
capturar líneas de log en un test:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const lines: string[] = []
const app = Arcton()
app.use(logger({ sink: line => lines.push(line) }))
app.get('/', () => 'ok')
app.listen()
```
## Loguear fuera del ciclo de request [#loguear-fuera-del-ciclo-de-request]
`logger()` devuelve el middleware con el `Logger` subyacente agregado como
`.logger`, así que el mismo logger se puede usar en cualquier otro lugar
de tu app — por ejemplo, justo después de `listen()`:
```ts
import { Arcton } from '@arcton/core'
import { logger } from '@arcton/logger'
const app = Arcton()
const log = logger()
app.use(log)
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
log.logger.info(`listening on ${server.url}`)
```
Ver [`logger()`](../api/logger.mdx) para la referencia completa de la API.
# OpenAPI & Scalar (/es/docs/integrations/openapi)
`@arcton/openapi` construye un documento OpenAPI 3.1 a partir de las rutas
con las que termina una app, y sirve una UI interactiva de
[Scalar](https://scalar.com) que lo lee. No hay ningún schema separado que
mantener — el documento se genera a partir de los mismos schemas
`params`/`query`/`body` con los que ya valida una ruta, más un contrato
`response` opcional.
`@arcton/core` no sabe que este paquete existe. `openapi()` es un
[middleware](../middleware/overview.mdx) común: regístralo con `app.use()` y
responde él mismo `GET /openapi.json` y `GET /docs`.
## Instalación [#instalación]
```bash
bun add @arcton/openapi
```
```bash
npm install @arcton/openapi
```
```bash
pnpm add @arcton/openapi
```
```bash
yarn add @arcton/openapi
```
## Uso básico [#uso-básico]
Registra `openapi()` con `app.use()`:
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
import * as z from 'zod'
const app = Arcton()
app.get('/users/:id', {
params: z.object({ id: z.uuid() }),
response: z.object({ id: z.string(), name: z.string() }),
handler: ctx => ({ id: ctx.params.id, name: 'Ada' })
})
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' }
})
)
app.listen({ port: 3000 })
```
Esto sirve `GET /openapi.json` (el documento) y `GET /docs` (Scalar, leyendo
ese mismo documento — nunca una segunda copia).
Al ser un middleware, corre en orden de registro como cualquier otro: uno
registrado después de un middleware de autenticación queda protegido por él;
uno registrado antes es público.
## Documentar una ruta [#documentar-una-ruta]
`params`, `query` y `body` ya se documentan solos — lo que le pasás a
Arcton para validar una ruta es exactamente lo que termina en el documento
generado. Un `body` declarado como schema se documenta como `application/json`;
declarado con `content`, se documenta cada media type que acepta la ruta con su
propio schema — ver
[Aceptar media types específicos](../validation/body.mdx#accepting-specific-media-types).
Dos campos más, ambos solo de documentación, completan una operación:
```ts
import { Arcton } from '@arcton/core'
import * as z from 'zod'
const app = Arcton()
app.get('/users/:id', {
params: z.object({ id: z.uuid() }),
response: {
200: z.object({ id: z.string(), name: z.string() }),
404: z.object({ message: z.string() })
},
detail: {
operationId: 'getUser',
summary: 'Get user',
tags: ['Users']
},
handler: ctx => ({ id: ctx.params.id, name: 'Ada' })
})
app.listen()
```
`response` es un mapa de status → schema; un schema suelto es un atajo para
`{ 200: schema }`. `detail` mapea `operationId`/`summary`/`description`/
`tags`/`deprecated` a la operación de OpenAPI. Ninguno de los dos se valida
en runtime — un handler que devuelve algo distinto responde exactamente
igual que si no existieran. Ver
[`response`/`detail`](../api/arcton-app.mdx#routeoptions) y
[`RouteDetail`](../api/arcton-app.mdx#routedetail).
Si omites `response`, la documentación incluye igualmente una respuesta `200`
genérica, pero no puede deducir la forma del valor retornado: los tipos de
TypeScript no existen en runtime y ejecutar el handler para muestrearlo podría
requerir contexto o producir efectos secundarios. Declara `response` cuando
quieras documentar el schema o códigos de estado concretos.
Un `response` declarado es el contrato completo: `{ 404: schema }` documenta
solo un `404`, sin agregar un `200` implícito.
## Requisitos del schema [#requisitos-del-schema]
Convertir un schema a OpenAPI depende de [Standard JSON
Schema](https://standardschema.dev/json-schema), una interfaz hermana de
[Standard Schema](https://standardschema.dev/), la que Arcton ya usa para
validar — Zod 4.6+ y ArkType 2.2+ la implementan de forma nativa. Valibot
todavía no; envuelve un schema con `toStandardJsonSchema()` de
[`@valibot/to-json-schema`](https://valibot.dev/guides/json-schema/) para
sumarse.
Un schema que no la implementa — o cuya forma no tiene equivalente en JSON
Schema, como un transform de Zod en la salida — degrada a un schema vacío
(`{}`) en vez de romper el build. Un parámetro de path o un body sigue
apareciendo en el documento con su nombre y ubicación; solo su tipo queda sin
especificar. Un schema de `query` es la excepción: sus parámetros se listan
leyendo las propiedades del schema, así que uno sin JSON Schema, o que no es
un objeto plano (una unión, por ejemplo), no agrega ningún parámetro de query.
Ver [Standard JSON
Schema](../api/validation-types.mdx#standardjsonschemav1).
## Configurando los paths [#configurando-los-paths]
Ambas rutas son configurables, y la UI de Scalar puede desactivarse por
completo:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users', () => [])
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
document: { path: '/schema.json' },
docs: { path: '/reference' }
})
)
app.listen()
```
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users', () => [])
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
docs: false // solo se sirve /openapi.json
})
)
app.listen()
```
## Configurando Scalar [#configurando-scalar]
La configuración propia de Scalar — theme, título de página, desde qué CDN
se carga su bundle — se mantiene separada de `info`/`servers`/`tags` del
documento, bajo `docs`:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
const app = Arcton()
app.get('/users', () => [])
app.use(
openapi({
info: { title: 'Users API', version: '1.0.0' },
docs: {
pageTitle: 'Users API Reference',
configuration: { theme: 'purple' }
}
})
)
app.listen()
```
`configuration` se pasa directo a Scalar — ver la [documentación de
configuración propia de
Scalar](https://guides.scalar.com/scalar/scalar-api-references/configuration)
para cada opción que acepta. El bundle de JS de Scalar se carga desde un
CDN por defecto; pasa `cdn` para apuntar a un build self-hosted.
## Modules y el árbol de rutas final [#modules-y-el-árbol-de-rutas-final]
El documento refleja el árbol de rutas final de la app, leído la primera vez
que se pide — incluyendo las rutas que vienen de [modules](../routing/modules.mdx), correctamente
prefijadas:
```ts
import { Arcton } from '@arcton/core'
import { openapi } from '@arcton/openapi'
import * as z from 'zod'
const users = Arcton({ prefix: '/users' })
users.get('/:id', {
response: z.object({ id: z.string() }),
handler: ctx => ({ id: ctx.params.id })
})
const app = Arcton({ prefix: '/api' })
app.use(users)
app.use(openapi({ info: { title: 'API', version: '1.0.0' } }))
app.listen()
// documenta GET /api/users/{id}
```
Una ruta wildcard (`*rest`) no tiene equivalente como path-template de
OpenAPI y se deja fuera del documento, y una ruta
[`ws()`](../api/arcton-app.mdx#ws) no tiene ningún contrato que documentar
en primer lugar — ambas siguen sirviendo con normalidad, solo que no
aparecen en `/openapi.json`.
Ver [`openapi()`](../api/openapi.mdx) para la referencia completa de la API.
# Architecture Overview (/es/docs/introduction/architecture-overview)
Una aplicación de Arcton tiene cuatro capas. Esta página es el mapa; cada
capa tiene una página más profunda bajo
[Arquitectura](../architecture/overview.mdx).
```text
Bun / Node.js el runtime
│
RuntimeAdapter @arcton/adapter-bun | @arcton/adapter-node
│ Request
▼
route tree matchea method + pathname
│ handler + params
▼
pipeline (steps) middleware · providers · validation
│ valor retornado
▼
response mapping valor → Response
```
## El adapter es dueño del runtime [#el-adapter-es-dueño-del-runtime]
`listen()` le entrega al adapter una función estilo `fetch` y una lista de
rutas WebSocket. El adapter levanta un servidor real, convierte lo que sea
que use el runtime en un `Request` estándar, y escribe de vuelta el
`Response`.
Como ese es todo el contrato, la misma aplicación corre en Bun o en Node.js
cambiando una sola opción:
```ts
import { Arcton } from '@arcton/core'
import { nodeAdapter } from '@arcton/adapter-node'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.listen({ adapter: nodeAdapter })
```
## El router matchea paths [#el-router-matchea-paths]
Las rutas se guardan en un árbol. Cada nodo tiene un map de hijos
estáticos más un slot dinámico y un slot wildcard, así que seguir un path
es una serie de búsquedas directas en vez de un escaneo sobre una lista de
patrones.
El matching prueba estático, después dinámico, después wildcard, y hace
backtracking cuando una rama llega a un callejón sin salida. Ver
[Precedence](../routing/precedence.mdx) para lo que eso significa cuando
escribes rutas que se solapan, y [Router](../architecture/router.mdx) para
por qué el árbol tiene esta forma.
## El pipeline se resuelve cuando te registras [#el-pipeline-se-resuelve-cuando-te-registras]
Cuando registras una ruta, Arcton captura el middleware y los providers que
existen en ese momento y guarda la cadena ya terminada junto con la ruta.
Nada se vuelve a resolver por request, y ninguna búsqueda en tiempo de
request puede cambiar qué middleware corre una ruta.
El orden dentro de esa cadena siempre es:
```text
global middleware → validation → route middleware → handler
```
con cada middleware envolviendo al siguiente, así que el código posterior a
`next()` se desenrolla en orden inverso. Ver
[Execution order](../middleware/execution-order.mdx).
## Las respuestas se mapean a partir de valores [#las-respuestas-se-mapean-a-partir-de-valores]
Lo que sea que el handler retorne se mapea a un `Response`: objetos a
JSON, strings a texto, tipos binarios a `application/octet-stream`, un
`Response` directo sin tocar. `ctx.response` lleva el status y los headers
acumulados en el camino. Ver [Response](../fundamentals/response.mdx).
## Los módulos se fusionan en un solo árbol [#los-módulos-se-fusionan-en-un-solo-árbol]
`app.use(module)` injerta el árbol de rutas de un módulo en el árbol del
padre en tiempo de registro, combinando prefixes y envolviendo los
handlers montados con el middleware del padre. Después de montar hay un
solo árbol y una sola búsqueda por request, sin importar cómo se organizó
la aplicación en el código fuente.
Ver [Modules](../routing/modules.mdx) y
[Module composition](../architecture/module-composition.mdx).
## Paquetes [#paquetes]
| Paquete | Rol |
| ---------------------- | ---------------------------------------------------------------- |
| `@arcton/core` | `Arcton()`, routing, pipeline, mapeo de respuestas |
| `@arcton/contracts` | los tipos que comparten ambos lados, incluyendo `RuntimeAdapter` |
| `@arcton/adapter-bun` | sirve sobre Bun |
| `@arcton/adapter-node` | sirve sobre Node.js |
| `@arcton/cors` | middleware de CORS |
| `arcton` | el CLI que scaffoldea un proyecto |
# Philosophy (/es/docs/introduction/philosophy)
Arcton toma un puñado de decisiones con carácter propio. Conocerlas hace que
el resto de la API sea predecible.
## El orden de registro es la semántica [#el-orden-de-registro-es-la-semántica]
La mayoría de los frameworks tratan el orden de las llamadas a `use()` como
una sugerencia. En Arcton es la regla, aplicada consistentemente: una ruta
corre el middleware y los providers que se registraron **antes que ella**, y
nada más.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/first', () => 'no timing header')
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set('X-Time', `${performance.now() - start}ms`)
})
app.get('/second', () => 'timed')
app.listen()
```
`/first` y `/second` tienen pipelines distintos, y el archivo se lee de
arriba hacia abajo exactamente como se comporta. La misma regla gobierna
`provide()`, el middleware con scope de path, y montar un módulo — una sola
idea en vez de cuatro.
[Execution order](../middleware/execution-order.mdx) cubre esto en
profundidad.
## Los tipos vienen de lo que escribiste [#los-tipos-vienen-de-lo-que-escribiste]
Arcton deriva los tipos del código que ya escribiste en vez de pedirte que
los declares dos veces. El literal de la ruta produce `ctx.params`. Un
schema produce la forma validada de `ctx.body`. Un provider amplía el
contexto para todo lo que viene después.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ startedAt: Date.now() }))
.get('/uptime/:unit', ctx => ({
unit: ctx.params.unit,
uptime: Date.now() - ctx.startedAt
}))
app.listen()
```
Nada de lo anterior nombra un tipo, y todo en él está tipado.
## Valores, no objetos de respuesta [#valores-no-objetos-de-respuesta]
Un handler retorna un valor. Arcton lo mapea a un `Response`. No hay ningún
`res.send()` que se te pueda olvidar, ni un doble envío que debuggear, y un
handler se mantiene como una función ordinaria que retorna datos — lo cual
es justo lo que lo hace fácil de testear.
Cuando una ruta necesita headers, un status code, o un stream, tanto
`ctx.response` como retornar un `Response` están disponibles.
## Composición sobre configuración [#composición-sobre-configuración]
El comportamiento surge de componer piezas pequeñas: un middleware, un
provider, un módulo. No hay un registro de plugins que aprender — una
funcionalidad reusable es una función que retorna un middleware, que es
exactamente cómo está construido
[`@arcton/cors`](../middleware/cors.mdx).
## El núcleo no conoce el runtime [#el-núcleo-no-conoce-el-runtime]
`@arcton/core` nunca importa una API de Bun o de Node.js. Todo lo que el
framework necesita de un runtime está descripto por la interfaz
`RuntimeAdapter` en `@arcton/contracts`, y un adapter la implementa. Eso
mantiene el código de routing y middleware idéntico entre runtimes, y hace
que soportar uno nuevo sea cuestión de escribir un solo archivo.
Ver [Runtime abstraction](../architecture/runtime-abstraction.mdx).
## El trabajo se hace en tiempo de registro [#el-trabajo-se-hace-en-tiempo-de-registro]
Arcton prefiere hacer el trabajo una sola vez, cuando las rutas se
registran, en vez de en cada request. Cada ruta guarda su propio pipeline
ya resuelto. Montar un módulo fusiona su árbol de rutas en el del padre en
vez de encadenar routers. `ctx.query` se parsea solo si algo lo lee.
El resultado es que un request hace lo mínimo: matchear un path, correr una
cadena ya preparada, mapear un valor.
## Explícito por sobre implícito [#explícito-por-sobre-implícito]
Arcton evita la magia que es cómoda una vez y confusa después. No hay un
namespace donde se escondan los valores del framework — los valores
provistos quedan directamente sobre el contexto. Un scope es un path
estático, no un segundo lenguaje de patrones. Las rutas en conflicto tiran
un error al registrarse en vez de pisarse silenciosamente entre sí.
# Runtime Support (/es/docs/introduction/runtime-support)
La misma aplicación corre en Bun y en Node.js. Qué runtime la sirve lo
decide el adapter que le pasas a `listen()`.
## Bun [#bun]
Bun es el default. No pasar ningún adapter usa `bunAdapter`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ runtime: 'bun' }))
app.listen({ port: 3000 })
```
Córrelo con `bun src/index.ts`. Para ser explícito, importa el adapter tú
mismo:
```ts
import { bunAdapter } from '@arcton/adapter-bun'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ runtime: 'bun' }))
app.listen({ adapter: bunAdapter })
```
## Node.js [#nodejs]
Instala `@arcton/adapter-node`:
```bash
bun add @arcton/adapter-node
```
```bash
npm install @arcton/adapter-node
```
```bash
pnpm add @arcton/adapter-node
```
```bash
yarn add @arcton/adapter-node
```
Luego pásaselo a `listen()`:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ runtime: 'node' }))
app.listen({ adapter: nodeAdapter })
```
Todo lo demás — rutas, middleware, providers, validation, mapeo de
respuestas — se comporta idéntico. Solo cambia el adapter.
## Qué hacen ambos adapters [#qué-hacen-ambos-adapters]
* Sirven la aplicación sobre HTTP y exponen el `port` y la `url` reales.
* Convierten el request nativo del runtime en un `Request` estándar, y
escriben de vuelta un `Response` estándar.
* Hacen el upgrade de las [rutas WebSocket](../routing/websockets.mdx)
registradas con `app.ws()`.
* Loguean con `console.error` un error tirado fuera del handler del
request y responden `500`.
## Diferencias que vale la pena conocer [#diferencias-que-vale-la-pena-conocer]
| | Bun | Node.js |
| ----------------- | --------------------- | ---------------------------------------- |
| Paquete | `@arcton/adapter-bun` | `@arcton/adapter-node` |
| `adapter.version` | `Bun.version` | la versión de Node.js sin la `v` inicial |
| `server.stop()` | retorna de inmediato | retorna una promesa para awaitear |
`stop()` es el que aparece en el código. En Node.js, úsalo con await:
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'ok')
const server = app.listen({ adapter: nodeAdapter })
process.on('SIGTERM', async () => {
await server.stop()
})
```
## Eligiendo un puerto [#eligiendo-un-puerto]
`port` por default es `3000`. Pasar `0` hace bind a un puerto libre, que es
como los tests evitan colisiones — lee el valor real de vuelta desde el
server:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => 'ok')
const server = app.listen({ port: 0 })
console.log(`listening on ${server.url}`)
```
Ver [Testing](../testing/overview.mdx) para el patrón completo.
## Otros runtimes [#otros-runtimes]
`RuntimeAdapter` es una interfaz pública en `@arcton/contracts`: un
`name`, una `version`, un objeto `capabilities` y una función `serve()`.
Cualquier runtime que pueda aceptar un `Request` y retornar un `Response`
puede respaldar uno. Ver [Runtime types](../api/runtime-types.mdx) y
[Adapters](../architecture/adapters.mdx).
# ¿Qué es Arcton? (/es/docs/introduction/what-is-arcton)
Arcton es un framework para construir APIs HTTP en TypeScript. Una
aplicación es una instancia de `Arcton()`: registras rutas sobre ella,
compones comportamiento alrededor de ellas, y la inicias con `listen()`.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
app.listen({ port: 3000 })
```
Eso es un archivo completo y ejecutable. `bun src/index.ts` lo sirve.
## Los handlers retornan valores [#los-handlers-retornan-valores]
Un handler retorna lo que sea que deba contener la respuesta. Arcton mapea
el valor retornado a una respuesta HTTP: un objeto se convierte en JSON, un
string se convierte en `text/plain`, un `Uint8Array` se convierte en un
cuerpo binario.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/json', () => ({ ok: true }))
app.get('/text', () => 'plain text')
app.get('/empty', () => {})
app.listen()
```
Cuando necesitas control total, retorna un `Response` y Arcton lo pasa sin
tocarlo. El mapeo completo está en [Response](../fundamentals/response.mdx).
## El literal de la ruta tipa el contexto [#el-literal-de-la-ruta-tipa-el-contexto]
Arcton lee el path que escribiste y tipa `ctx.params` a partir de él:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:userId/posts/:postId', ctx => {
// ctx.params is { userId: string; postId: string }
return { user: ctx.params.userId, post: ctx.params.postId }
})
app.listen()
```
Escribir mal `ctx.params.userID` es un error de compilación, no un
`undefined` en runtime.
## El contexto crece a medida que compones [#el-contexto-crece-a-medida-que-compones]
`provide()` agrega valores al contexto y amplía su tipo para todo lo que se
registre después:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(ctx => ({
requestId: ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
}))
.get('/whoami', ctx => ({ requestId: ctx.requestId }))
app.listen()
```
`ctx.requestId` está tipado en el handler porque el provider se registró
antes que la ruta. Ver [Providers](../providers/overview.mdx).
## Las aplicaciones se construyen a partir de módulos [#las-aplicaciones-se-construyen-a-partir-de-módulos]
Un módulo es una instancia de `Arcton()` con su propio prefix. Montar uno
fusiona sus rutas en el árbol de rutas del padre:
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/', () => [{ id: '1' }])
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton({ prefix: '/api' })
app.use(users)
app.listen()
```
Esto sirve `GET /api/users` y `GET /api/users/:id`. Ver
[Modules](../routing/modules.mdx).
## Runtimes [#runtimes]
El núcleo no depende de ningún runtime específico. Bun y Node.js están
soportados a través de adapters, elegidos en `listen()`:
```ts
import { Arcton } from '@arcton/core'
import { nodeAdapter } from '@arcton/adapter-node'
const app = Arcton()
app.get('/', () => 'Hello from Node.js')
app.listen({ adapter: nodeAdapter })
```
Ver [Runtime support](./runtime-support.mdx).
## Qué incluye Arcton [#qué-incluye-arcton]
* Un árbol de rutas con segmentos estáticos, dinámicos y wildcard, con
[precedencia](../routing/precedence.mdx) definida.
* [Middleware](../middleware/overview.mdx) global, con scope de path, o
atado a una sola ruta.
* [Validación](../validation/overview.mdx) por ruta de params, query y body
a través de [Standard Schema](https://standardschema.dev/), así que Zod,
Valibot y ArkType funcionan todos.
* [Body parsing](../validation/body-parsers.mdx) por `Content-Type`,
extensible con tus propios parsers.
* [Rutas WebSocket](../routing/websockets.mdx).
* [CORS](../middleware/cors.mdx) como paquete separado.
* Adapters de [Bun y Node.js](../api/adapters.mdx), y la interfaz
`RuntimeAdapter` detrás de ellos.
# When to Use Arcton (/es/docs/introduction/when-to-use)
Arcton apunta a servicios HTTP en TypeScript donde la forma de un request
importa: parámetros tipados, input validado, y una aplicación que crece en
módulos sin convertirse en una pila de routers.
## Buenos casos de uso [#buenos-casos-de-uso]
**APIs JSON.** Los handlers retornan valores y Arcton los serializa, así
que un endpoint CRUD es una función que retorna un objeto.
**Servicios con input validado.** Params, query y body toman cada uno un
[Standard Schema](https://standardschema.dev/), y lo que llega al handler
es la salida validada, ya coercionada y tipada.
**Aplicaciones organizadas por dominio.** Cada área de la app es un módulo
con su propio prefix, desarrollado en su propio archivo y montado en el
padre — ver [Modules](../routing/modules.mdx).
**Proyectos a los que les importa el path del request.** El árbol de
rutas, el pipeline resuelto por ruta, y el parseo perezoso de query mueven
todo el trabajo al tiempo de registro.
**Código que debería correr en más de un runtime.** La aplicación se
escribe contra Arcton; Bun o Node.js es un argumento de `listen()`.
**Tiempo real junto con HTTP.** `app.ws()` registra rutas WebSocket en el
mismo servidor que las rutas HTTP.
## Comparaciones conceptuales [#comparaciones-conceptuales]
Estas son analogías para orientarte, no afirmaciones de compatibilidad.
Arcton tiene su propia API, y el código no se porta sin cambios.
**Si vienes de Express.** El middleware te va a resultar familiar: una
función que recibe el contexto del request y un `next` que puede
awaitear, con código después de `await next()` corriendo a la salida. Dos
cosas difieren. Los handlers retornan un valor en vez de llamar a un
método `res`, y `use()` aplica a las rutas registradas después en vez de
a todo el archivo. Ver
[Execution order](../middleware/execution-order.mdx).
**Si vienes de Hono o Elysia.** El handler que retorna un valor y el
modelo de runtime-adapter te van a resultar familiares. Arcton deriva
`ctx.params` del literal de la ruta con el mismo espíritu, mantiene los
valores provistos planos sobre el contexto a través de
[`provide()`](../providers/overview.mdx), y fusiona módulos en un único
árbol de rutas al registrarse.
**Si vienes de NestJS.** La unidad de organización aquí también es un
módulo, pero es una instancia simple de `Arcton()` en vez de una clase
con decorators, y `provide()` compone contexto tipado por request en vez
de resolver un grafo de dependencias. Si quieres inyección por
constructor y decorators, ese es un modelo distinto al que ofrece
Arcton.
**Si vienes de Fastify.** La validación basada en schemas te va a resultar
natural. Arcton acepta cualquier librería de Standard Schema en vez de
una específica, y el tipo de salida del schema fluye hacia el handler.
## Qué esperar de un pre-1.0 [#qué-esperar-de-un-pre-10]
Arcton está en pre-1.0 y la API puede cambiar entre releases. Fija tus
dependencias y lee las notas de release antes de actualizar.
## Siguiente [#siguiente]
# CORS (/es/docs/middleware/cors)
Instala `@arcton/cors`:
```bash
bun add @arcton/cors
```
```bash
npm install @arcton/cors
```
```bash
pnpm add @arcton/cors
```
```bash
yarn add @arcton/cors
```
Luego regístralo como middleware global:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(cors())
app.get('/users', () => [{ id: '1' }])
app.listen()
```
Sin opciones, el middleware permite cualquier origen. Regístralo antes
de tus rutas, para que cada ruta debajo quede cubierta — mira
[Execution order](./execution-order.mdx).
## Permitir orígenes específicos [#permitir-orígenes-específicos]
`origin` acepta un string, un array, o una función:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(cors({ origin: 'https://app.example.com' }))
app.get('/users', () => [{ id: '1' }])
app.listen()
```
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: ['https://app.example.com', 'https://admin.example.com']
})
)
app.get('/users', () => [{ id: '1' }])
app.listen()
```
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: origin => origin.endsWith('.example.com')
})
)
app.get('/users', () => [{ id: '1' }])
app.listen()
```
La función recibe el origin del request y el propio `Request`, así que
una decisión puede depender del path o de un header.
Cuando el origin permitido es cualquier cosa distinta de `'*'`, el
origin que matcheó se devuelve tal cual y se agrega `Vary: Origin`,
así que las cachés distinguen la respuesta por origin. Un request cuyo
origin no está permitido sigue hacia tu ruta sin ningún header de CORS
agregado, y el navegador bloquea el resultado del lado del cliente.
## Opciones [#opciones]
| Opción | Default | Efecto |
| ---------------- | ------------------------------ | ----------------------------------------------------- |
| `origin` | `'*'` | qué orígenes están permitidos |
| `methods` | repite lo que pidió el request | `Access-Control-Allow-Methods` en el preflight |
| `allowedHeaders` | repite lo que pidió el request | `Access-Control-Allow-Headers` en el preflight |
| `exposedHeaders` | — | `Access-Control-Expose-Headers` en la respuesta |
| `credentials` | `false` | agrega `Access-Control-Allow-Credentials` |
| `maxAge` | — | `Access-Control-Max-Age` en el preflight, en segundos |
| `preflight` | `true` | si responde o no los requests de preflight |
## Requests con credenciales [#requests-con-credenciales]
Los navegadores rechazan una respuesta con credenciales que permite
cualquier origen, así que nombra los orígenes en los que confías:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: 'https://app.example.com',
credentials: true,
exposedHeaders: ['X-Total-Count']
})
)
app.get('/users', ctx => {
ctx.response.headers.set('X-Total-Count', '1')
return [{ id: '1' }]
})
app.listen()
```
Combinar `origin: '*'` con `credentials: true` tira un `TypeError`
cuando se llama a `cors()`, al arrancar en vez de en el primer
request.
## Preflight [#preflight]
Un navegador envía `OPTIONS` con `Access-Control-Request-Method` antes
de ciertos requests cross-origin. `cors()` responde esos por su cuenta
con `204` y los headers ya calculados:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use(
cors({
origin: 'https://app.example.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 600
})
)
app.post('/users', () => ({ created: true }))
app.listen()
```
Con `methods` o `allowedHeaders` omitidos, la respuesta de preflight
repite lo que pidió el request.
Solo se intercepta un preflight real — un request `OPTIONS` sin
`Access-Control-Request-Method` pasa directo hacia
[tu propia ruta `app.options()`](../routing/http-methods.mdx).
## Cubrir cada respuesta [#cubrir-cada-respuesta]
Como `cors()` es middleware global, sus headers también llegan a las
respuestas `404` y `405` que genera Arcton, que es lo que un navegador
necesita para reportar el status real en vez de una falla de CORS. Mira
[Global middleware](./global.mdx).
## Aplicar un scope [#aplicar-un-scope]
Para aplicar CORS a una sola sección, asígnale un scope:
```ts
import { Arcton } from '@arcton/core'
import { cors } from '@arcton/cors'
const app = Arcton()
app.use('/public', cors({ origin: '*' }))
app.get('/public/status', () => ({ ok: true }))
app.get('/internal/status', () => ({ ok: true }))
app.listen()
```
Un registro [con scope](./scoped.mdx) cubre las rutas matcheadas bajo
ese path.
Mira [`cors()` en la referencia de la API](../api/cors.mdx) para la
firma completa.
# Execution Order (/es/docs/middleware/execution-order)
Dos reglas explican cada pregunta de orden en Arcton:
1. **Una ruta corre el middleware y los providers registrados antes que
ella.**
2. **Dentro de ese conjunto, el orden es** global → validation → route
middleware → handler.
## El snapshot de registro [#el-snapshot-de-registro]
Cuando registras una ruta, Arcton toma el middleware y los providers
que existen en ese momento y guarda la cadena ya terminada junto con la
ruta. Las llamadas hechas después no la alcanzan.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/before', () => ({ timed: false }))
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set('X-Time', `${performance.now() - start}ms`)
})
app.get('/after', () => ({ timed: true }))
app.listen()
```
`/after` recibe el header `X-Time`. `/before` no — se registró cuando
ese middleware todavía no existía.
Por eso el archivo se lee tal como se comporta: mover una llamada a
`use()` hacia arriba o hacia abajo cambia exactamente las rutas debajo
de ella.
La regla práctica: registra el middleware global y los providers al
principio del archivo, antes de cualquier ruta. Así cada ruta los ve
a todos.
## El orden adentro de un request [#el-orden-adentro-de-un-request]
Para una ruta matcheada:
```text
request
│
▼
┌─ match path + method ───────────────┐
│ │
▼ │
global middleware (en orden de registro, la más exterior primero)
│ │
▼ │
validation (params → query → body)
│ │
▼ │
route middleware (en el orden escrito, la más interior)
│ │
▼ │
handler │
│ │
└─ vuelta: route mw → global mw ──────┘
│
▼
response mapping
```
Visto en código:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.use(async (ctx, next) => {
console.log('1 global in')
await next()
console.log('6 global out')
})
app.get('/users/:id', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
middleware: [
async (ctx, next) => {
console.log('3 route in')
await next()
console.log('5 route out')
}
],
handler: ctx => {
console.log('4 handler')
return { id: ctx.params.id }
}
})
app.listen()
```
`GET /users/42` loguea `1 global in`, después corre la validation (paso
2, en silencio), después `3 route in`, `4 handler`, `5 route out`,
`6 global out`.
Como la validation queda entre medio, el middleware global ve el string
crudo `ctx.params.id`, mientras que el middleware de ruta y el handler
ven el número.
## Los providers siguen la misma regla [#los-providers-siguen-la-misma-regla]
[`provide()`](../providers/overview.mdx) comparte la secuencia con
`use()`, así que aplica el mismo snapshot:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ startedAt: Date.now() }))
.get('/uptime', ctx => ({ uptime: Date.now() - ctx.startedAt }))
app.listen()
```
Registrar la ruta antes que el provider sería un error de compilación,
porque `ctx.startedAt` todavía no sería parte del tipo del context. El
sistema de tipos y el runtime están de acuerdo aquí: leen la misma
lista, en el mismo orden.
## Middleware con scope [#middleware-con-scope]
Un [scope](./scoped.mdx) se aplica encima del snapshot: cuando una ruta
se registra, Arcton conserva el middleware con scope cuyo path
contiene a esa ruta, y descarta el resto.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
console.log('global')
await next()
})
app.use('/admin', async (ctx, next) => {
console.log('admin only')
await next()
})
app.get('/admin/stats', () => ({ users: 42 })) // both
app.get('/health', () => ({ status: 'ok' })) // global only
app.listen()
```
La decisión ocurre una sola vez, al registrarse. Nada se vuelve a
verificar por request.
## La excepción: 404 y 405 [#la-excepción-404-y-405]
Las respuestas que Arcton genera porque nada matcheó se comportan
distinto: **el middleware global corre sobre ellas sin importar el
orden de registro.**
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('Access-Control-Allow-Origin', '*')
})
app.listen()
```
`GET /missing` responde `404` **con** el header de CORS, aunque el
middleware se registró después de todas las rutas.
La razón es que la regla del snapshot es sobre una ruta: "antes" y
"después" solo significan algo en relación al propio registro de una
ruta. Un `404` no tiene ninguna ruta, así que no hay nada respecto de
lo cual estar antes o después — y las cosas que pertenecen a esas
respuestas (CORS, logging, request ids) son exactamente las que deben
cubrir cada respuesta. Arcton junta el middleware `use()` sin scope una
sola vez cuando se llama a `listen()`, y lo aplica ahí.
Qué **no** corre en `404`/`405`:
| | Ruta matcheada | `404` / `405` |
| ------------------------ | ------------------------- | ------------- |
| `use(middleware)` | solo antes | siempre |
| `use(scope, middleware)` | solo antes, bajo el scope | no |
| middleware de ruta | sí | no |
| `provide()` | solo antes | no |
| validation | sí | no |
## Módulos [#módulos]
Montar un [módulo](../routing/modules.mdx) sigue la misma regla desde
el lado del padre: el middleware global y los providers del padre
registrados antes de `app.use(module)` envuelven cada ruta que trae el
módulo, y cualquier cosa registrada después no lo hace.
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.use(async (ctx, next) => {
ctx.response.headers.set('X-Before', 'yes')
await next()
})
app.use(users)
app.use(async (ctx, next) => {
ctx.response.headers.set('X-After', 'no')
await next()
})
app.listen()
```
`GET /users/1` lleva `X-Before` y no `X-After`.
El propio middleware del módulo sigue funcionando después de montarlo,
y corre adentro del middleware del padre.
## Por qué funciona así [#por-qué-funciona-así]
Resolver la cadena una sola vez, al registrarse, hace que un request
nunca tenga que preguntar "¿qué middleware aplica aquí?" — la respuesta
ya se calculó cuando se creó la ruta. También hace honesto al sistema
de tipos: `ctx` se tipa a partir de los providers registrados antes del
handler, que es exactamente el conjunto que va a correr.
Ver [Pipeline](../architecture/pipeline.mdx) para cómo se construye la
cadena.
# Global Middleware (/es/docs/middleware/global)
`app.use(middleware)` aplica un middleware a cada ruta registrada
después de la llamada:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
console.log(`→ ${ctx.request.method} ${new URL(ctx.request.url).pathname}`)
await next()
})
app.get('/', () => ({ ok: true }))
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
Ambas rutas loguean. Registra el middleware global cerca del principio
del archivo, antes de las rutas que debería cubrir — ver
[Execution order](./execution-order.mdx).
## Varios middleware [#varios-middleware]
Llama a `use()` una vez por middleware. Se anidan en orden de registro,
así que el primero registrado es el más exterior:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set('X-Time', `${performance.now() - start}ms`)
})
app.use(async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
await next()
})
app.get('/', () => ({ ok: true }))
app.listen()
```
## También cubre 404 y 405 [#también-cubre-404-y-405]
El middleware global corre sobre las respuestas que Arcton genera
cuando ninguna ruta matchea el path, o cuando el path matchea pero el
método no:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('Access-Control-Allow-Origin', '*')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
`GET /missing` responde `404` **con** el header
`Access-Control-Allow-Origin`. Eso es lo que hace del middleware global
el lugar correcto para cosas que deben cubrir cada respuesta HTTP —
headers de CORS, logging de requests, timing de respuestas.
En `404` y `405`, el middleware global corre sin importar dónde esté
ubicado en relación con tus rutas: un `use()` escrito después de todas
tus rutas igual aplica. Una ruta matcheada, en cambio, solo corre el
middleware registrado antes de ella.
[Execution order](./execution-order.mdx) explica por qué las dos
reglas difieren.
El [middleware con scope](./scoped.mdx) y el
[middleware de ruta](./route-level.mdx) no corren sobre esas respuestas,
porque no hay ninguna ruta matcheada a la que puedan pertenecer.
## Leer el request [#leer-el-request]
El context lleva el `Request` estándar, así que todo lo que puedes hacer
con la Fetch API está disponible:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const auth = ctx.request.headers.get('authorization')
if (auth === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
El middleware global corre antes de la
[validation](../validation/overview.mdx), así que ve los valores
crudos: `ctx.params` y `ctx.query` siguen siendo strings ahí, incluso
en una ruta cuyo schema los convierte.
## Agregar valores al context [#agregar-valores-al-context]
Cuando un middleware existe solo para calcular un valor que el handler
necesita, usa [`provide()`](../providers/overview.mdx) en su lugar —
pone el valor sobre el context y lo tipa para todo lo que se registre
después.
# Modifying Responses (/es/docs/middleware/modifying-responses)
`ctx.response` lleva el status y los headers que se van a usar para la
respuesta. El middleware puede leerlo y cambiarlo a la entrada y a la
salida:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('X-Powered-By', 'Arcton')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
## Headers [#headers]
`ctx.response.headers` es un objeto `Headers` estándar. `set()`
reemplaza, `append()` agrega otro valor:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
ctx.response.headers.append('Set-Cookie', 'session=abc; Path=/; HttpOnly')
ctx.response.headers.append('Set-Cookie', 'theme=dark; Path=/')
})
app.get('/', () => ({ ok: true }))
app.listen()
```
Los cambios de headers funcionan tanto antes como después de
`await next()`, y ambos envían las cookies de arriba. Asignar un
header que el handler también asigna hace que gane la escritura más
tardía, así que un middleware que corre después de `next()` puede
sobrescribir al handler.
## Status [#status]
Asigna `ctx.response.status` antes de que el body se produzca — en el
handler, o en un middleware antes de `await next()`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/users', ctx => {
ctx.response.status = 201
ctx.response.headers.set('Location', '/users/42')
return { id: '42' }
})
app.listen()
```
El status queda fijo una vez que se produce el body de la respuesta.
Asignar `ctx.response.status` después de `await next()` tira un
`TypeError`. Para cambiar un status a la salida, retorna un valor
nuevo o un `Response` en su lugar — mira abajo.
## Reemplazar el body después de next() [#reemplazar-el-body-después-de-next]
Retornar un valor después de `await next()` reemplaza el body. Los
headers y el status acumulados hasta ese momento se conservan:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
return { wrapped: true, at: new Date().toISOString() }
})
app.get('/', () => ({ ok: true }))
app.listen()
```
El cliente recibe el objeto envoltorio.
Para reemplazar también el status, retorna un `Response`. Gana sin
condiciones — no se fusiona ningún header de `ctx.response`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
await next()
if (ctx.response.headers.get('X-Deprecated') === 'yes') {
return new Response(JSON.stringify({ error: 'gone' }), {
status: 410,
headers: { 'content-type': 'application/json' }
})
}
})
app.get('/legacy', ctx => {
ctx.response.headers.set('X-Deprecated', 'yes')
return { ok: true }
})
app.listen()
```
## Cortar la cadena [#cortar-la-cadena]
Retornar un valor **sin** llamar a `next()` responde el request de
inmediato, y nada más de la cadena corre:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
if (ctx.request.headers.get('x-api-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
Un corte de cadena también puede retornar un valor simple, que se
mapea de la misma forma que el valor de retorno de un handler:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
if (!ctx.request.headers.has('authorization')) {
ctx.response.status = 401
return { error: 'missing authorization' }
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
## Caché y respuestas condicionales [#caché-y-respuestas-condicionales]
Como el middleware ve la respuesta a la salida, puede agregar headers
de caché a toda una sección de la API:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/static', async (ctx, next) => {
await next()
ctx.response.headers.set('Cache-Control', 'public, max-age=3600')
})
app.get('/static/config', () => ({ theme: 'dark' }))
app.listen()
```
## Ejemplo completo [#ejemplo-completo]
Timing, un request id y cookies juntos:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const start = performance.now()
const requestId = ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
await next()
ctx.response.headers.set('X-Request-Id', requestId)
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
})
app.get('/', ctx => {
ctx.response.status = 200
ctx.response.headers.append('Set-Cookie', 'visited=1; Path=/')
return { ok: true }
})
app.listen()
```
Para ver cómo un valor retornado se convierte en un `Response`, mira
[Response](../fundamentals/response.mdx).
# Middleware Overview (/es/docs/middleware/overview)
Un middleware es una función que corre alrededor de tus handlers. Recibe
el [context](../fundamentals/context.mdx) y una función `next`, y
decide qué pasa antes y después del resto de la cadena:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
})
app.get('/', () => ({ ok: true }))
app.listen()
```
Todo lo que está antes de `await next()` corre a la entrada. Todo lo que
está después corre a la salida, una vez que el handler y cada middleware
interior terminaron.
## El onion [#el-onion]
El middleware se anida. Con dos registrados, el flujo a través de un
request es:
```text
┌── middleware A ─────────────────────────┐
│ ┌── middleware B ──────────────────┐ │
│ │ ┌── handler ───────────────┐ │ │
│ │ │ retorna un valor │ │ │
│ │ └──────────────────────────┘ │ │
│ │ después de await next() │ │
│ └──────────────────────────────────┘ │
│ después de await next() │
└─────────────────────────────────────────┘
```
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
console.log('A: in')
await next()
console.log('A: out')
})
app.use(async (ctx, next) => {
console.log('B: in')
await next()
console.log('B: out')
})
app.get('/', () => {
console.log('handler')
return { ok: true }
})
app.listen()
```
Un request a `/` loguea `A: in`, `B: in`, `handler`, `B: out`, `A: out`.
## Tres formas de agregar uno [#tres-formas-de-agregar-uno]
| Forma | Aplica a |
| ------------------------------------ | -------------------------------------------------------------------------- |
| `app.use(middleware)` | cada ruta registrada después de la llamada, más las respuestas `404`/`405` |
| `app.use('/admin', middleware)` | rutas bajo ese path, registradas después de la llamada |
| `app.get(path, middleware, handler)` | solo esa ruta |
```ts
import { Arcton } from '@arcton/core'
import type { Middleware } from '@arcton/contracts'
const requestId: Middleware = async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
await next()
}
const app = Arcton()
app.use(requestId) // global
app.use('/admin', requestId) // scoped
app.get('/health', requestId, () => ({ ok: true })) // route level
app.listen()
```
Cada forma tiene su propia página: [Global](./global.mdx),
[Scoped](./scoped.mdx) y [Route level](./route-level.mdx).
Qué middleware corre una ruta se decide cuando la ruta se registra, a
partir de las llamadas hechas antes de ella.
[Execution order](./execution-order.mdx) es la página para leer una vez
que lo básico está claro.
## Short-circuiting [#short-circuiting]
Un middleware que retorna un valor sin llamar a `next()` responde el
request por su cuenta. El handler y todo lo de adentro nunca corren:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use(async (ctx, next) => {
if (ctx.request.headers.get('x-api-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/private', () => ({ secret: true }))
app.listen()
```
El valor retornado pasa por el mismo
[mapeo de respuestas](../fundamentals/response.mdx) que el de un
handler, así que retornar un objeto produce JSON y retornar un
`Response` lo pasa directo.
## Tipar un middleware [#tipar-un-middleware]
`Middleware` se exporta desde `@arcton/contracts`. Declarar el tipo le
da a un middleware independiente sus tipos de parámetro:
```ts
import type { Middleware } from '@arcton/contracts'
export const logger: Middleware = async (ctx, next) => {
const { method, url } = ctx.request
console.log(`→ ${method} ${new URL(url).pathname}`)
await next()
}
```
Eso es un fragmento — impórtalo en un archivo que arme una app para
correrlo.
## Middleware reusable [#middleware-reusable]
Un middleware que toma opciones es simplemente una función que retorna
uno:
```ts
import type { Middleware } from '@arcton/contracts'
export function requireHeader(name: string): Middleware {
return async (ctx, next) => {
if (!ctx.request.headers.has(name)) {
return new Response(`Missing ${name}`, { status: 400 })
}
await next()
}
}
```
Esa es la misma forma que usa [`@arcton/cors`](./cors.mdx).
# Route Middleware (/es/docs/middleware/route-level)
Pasa middleware antes del handler para agregarlo a una sola ruta:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get(
'/reports',
async (ctx, next) => {
if (ctx.request.headers.get('authorization') === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
},
() => ({ reports: [] })
)
app.listen()
```
El último argumento siempre es el handler; todo lo anterior es
middleware, que corre en el orden en que se escribió. Se puede pasar
cualquier cantidad:
```ts
import { Arcton } from '@arcton/core'
import type { Middleware } from '@arcton/contracts'
const authenticate: Middleware = async (ctx, next) => {
if (ctx.request.headers.get('authorization') === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
}
const audit: Middleware = async (ctx, next) => {
await next()
console.log(`audited ${new URL(ctx.request.url).pathname}`)
}
const app = Arcton()
app.delete('/users/:id', authenticate, audit, ctx => ({
deleted: ctx.params.id
}))
app.listen()
```
## El middleware de ruta se tipa por su ruta [#el-middleware-de-ruta-se-tipa-por-su-ruta]
Un middleware escrito en línea recibe los tipos de parámetro de la
ruta:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get(
'/users/:id',
async (ctx, next) => {
console.log(`looking up user ${ctx.params.id}`)
await next()
},
ctx => ({ id: ctx.params.id })
)
app.listen()
```
Un middleware declarado por separado como `Middleware` es reusable
entre rutas y ve `ctx.params` como `Record`.
## Con la forma de opciones [#con-la-forma-de-opciones]
Cuando una ruta usa la [forma de opciones](../validation/overview.mdx),
el middleware va en el array `middleware`:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
body: v.object({
item: v.string(),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
middleware: [
async (ctx, next) => {
console.log(`order for user ${ctx.params.id}: ${ctx.body.item}`)
await next()
}
],
handler: ctx => ({ userId: ctx.params.id, order: ctx.body })
})
app.listen()
```
El middleware de ruta corre **después** de la validation, así que ve
los valores ya validados y convertidos: `ctx.params.id` aquí es un
número, y `ctx.body` está tipado a partir del schema.
## Dónde se ubica en la cadena [#dónde-se-ubica-en-la-cadena]
El middleware de ruta es la capa más interior, la más cercana al
handler:
```text
global middleware → validation → route middleware → handler
```
Así que un middleware global envuelve a un middleware de ruta, que
envuelve al handler. Ver [Execution order](./execution-order.mdx).
Como el middleware de ruta pertenece a una ruta matcheada, no corre
sobre las respuestas `404` y `405` que genera Arcton.
## Elegir una forma [#elegir-una-forma]
| Usar | Cuándo |
| ---------------------- | -------------------------------------------------- |
| Route middleware | una o dos rutas necesitan el comportamiento |
| [Scoped](./scoped.mdx) | toda una sección de la API lo necesita |
| [Global](./global.mdx) | cada respuesta lo necesita, incluyendo `404`/`405` |
# Scoped Middleware (/es/docs/middleware/scoped)
Pasar un path antes del middleware lo limita a las rutas bajo ese path:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/admin/stats', () => ({ users: 42 }))
app.get('/health', () => ({ status: 'ok' }))
app.listen()
```
`/admin/stats` está protegida. `/health` no lo está.
## Qué significa "bajo un path" [#qué-significa-bajo-un-path]
Un scope matchea el path en sí y cualquier cosa debajo de él, comparado
segmento por segmento — no como un prefijo de string:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/api', async (ctx, next) => {
ctx.response.headers.set('X-Scoped', 'yes')
await next()
})
app.get('/api', () => ({ root: true })) // matches the scope itself
app.get('/api/users', () => ({ users: [] })) // matches, nested
app.get('/apidocs', () => ({ docs: true })) // does NOT match
app.listen()
```
`/apidocs` empieza con las mismas letras que `/api`, pero no está debajo
de él.
## Un scope es un path static [#un-scope-es-un-path-static]
Los scopes son paths simples — los segmentos `:param` y `*wildcard` no
son parte de esta forma:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.use('/users', async (ctx, next) => {
ctx.response.headers.set('X-Section', 'users')
await next()
})
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
El scope `'/users'` cubre `/users/:id` porque esa ruta vive debajo de
él. Ver [Registration errors](../errors/registration-errors.mdx) para
el error que produce un scope no static.
## El orden sigue aplicando [#el-orden-sigue-aplicando]
Igual que el middleware global, un scope solo alcanza a las rutas
registradas después de él:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/admin/early', () => ({ guarded: false }))
app.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
app.get('/admin/late', () => ({ guarded: true }))
app.listen()
```
Solo `/admin/late` está protegida. Registra el scope antes de las rutas
que protege — ver [Execution order](./execution-order.mdx).
## Middleware con scope y rutas matcheadas [#middleware-con-scope-y-rutas-matcheadas]
El middleware con scope solo corre para rutas que matchearon. No corre
sobre las respuestas `404` y `405` que genera Arcton, ya que esas no
tienen ninguna ruta a la que pertenecer. Cuando algo tiene que llegar a
cada respuesta, regístralo [globalmente](./global.mdx) en su lugar.
## Scopes adentro de módulos [#scopes-adentro-de-módulos]
Un [módulo](../routing/modules.mdx) puede darle scope a su propio
middleware, y el scope se compara contra el path tal como se escribió
adentro del módulo — no contra el path ya montado:
```ts
import { Arcton } from '@arcton/core'
const api = Arcton({ prefix: '/api' })
api.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
api.get('/admin/stats', () => ({ users: 42 }))
const app = Arcton()
app.use(api)
app.listen()
```
La ruta se sirve en `/api/admin/stats` y el scope se escribe `'/admin'`,
coincidiendo con cómo se escribió la ruta adentro del módulo.
Un scope pertenece a la instancia en la que se registra. El
middleware con scope de un padre no alcanza las rutas de un módulo
montado — pon el middleware con scope en el módulo dueño de esas
rutas.
# Descripción general de Providers (/es/docs/providers/overview)
`provide()` compone context tipado: corre una función por request y mezcla lo que sea
que devuelva, plano y tipado, sobre `ctx`, para todo lo que se registre después:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(ctx => ({
requestId: ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
}))
.get('/whoami', ctx => ({ requestId: ctx.requestId }))
app.listen()
```
`ctx.requestId` pasa el type-check en el handler de arriba porque `.get()` está
encadenado directamente sobre el valor que devuelve `.provide()` — ese es el objeto
cuyo tipo realmente trae `requestId`. Ver [Context tipado](./typed-context.mdx) para
saber exactamente por qué importa el encadenamiento.
## Los providers pueden construir uno sobre otro [#los-providers-pueden-construir-uno-sobre-otro]
Los providers corren en orden de registro, y uno posterior puede leer lo que agregó
uno anterior:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ db: { query: async (_sql: string) => [] } }))
.provide(async ctx => {
const users = await ctx.db.query('select * from users')
return { users }
})
.get('/users', ctx => ctx.users)
app.listen()
```
## Lo que no puedes proveer [#lo-que-no-puedes-proveer]
Volver a proveer una key que ya está en `ctx` — una que ya proveíste antes, o uno de
los campos base `request`, `params`, `query`, `response`, `body` — es un error de
compilación, no algo que se chequea en runtime.
Los providers corren antes de la validación y del route middleware, y no corren para
responses `404`/`405`. Para ver con más profundidad cómo `provide()` compone context
tipado, ver [Context tipado](./typed-context.mdx); para saber cuándo usar `provide()`
en vez de `use()`, ver [Providers vs Middleware](./providers-vs-middleware.mdx).
# Providers vs Middleware (/es/docs/providers/providers-vs-middleware)
`provide()` y `use()` corren ambos por request, en orden de registro, y se pueden
mezclar libremente — pero existen para trabajos distintos.
Un provider no tiene `next` y no puede cortar la cadena; lo que devuelve se mezcla
sobre `ctx` y la cadena siempre continúa. El middleware recibe `next`, corre código
antes y después de llamarlo, y puede cortar la cadena devolviendo un valor sin llamar
a `next()` — deteniendo todo lo que sigue, incluyendo cualquier provider o handler
que de otra forma correría.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.use(async (ctx, next) => {
console.log(ctx.request.method, new URL(ctx.request.url).pathname)
await next()
})
.provide(ctx => {
const authHeader = ctx.request.headers.get('authorization')
return {
user: authHeader === 'secret' ? { id: 1, name: 'Alice' } : null
}
})
.get(
'/profile',
async (ctx, next) => {
if (!ctx.user) return new Response('Unauthorized', { status: 401 })
await next()
},
ctx => ({ user: ctx.user })
)
app.listen()
```
El `use()` de logging de arriba solo observa la request; no agrega nada al tipo de
`ctx`. La llamada a `provide()` adjunta `user`, tipado, a todo lo que se registre
después. El route middleware en `/profile` es la pieza que realmente puede rechazar
la request — devolviendo `401` y sin llamar nunca a `next()` — algo que un provider no
tiene ningún mecanismo para hacer.
Recurre a `provide()` cuando estás adjuntando un valor tipado que todo lo que sigue
debería poder leer. Recurre a `use()` cuando necesitas correr código alrededor del
resto de la cadena, inspeccionar o reemplazar la response, o detener la request
temprano. Ver [Descripción general de Providers](./overview.mdx) y
[Descripción general de Middleware](../middleware/overview.mdx) para cada uno por
separado.
# Context tipado (/es/docs/providers/typed-context)
Cada llamada a `provide()` devuelve un nuevo valor de app cuyo tipo trae el campo
agregado, para lo que sea que se registre sobre *ese valor devuelto* después:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/before', () => {
// ctx has no `user` here — the provide() below hasn't run yet
// in registration order
return { ok: true }
})
.provide(ctx => ({
user: ctx.request.headers.get('authorization') ? { id: 1 } : null
}))
.get('/after', ctx => ({ user: ctx.user }))
app.listen()
```
`ctx.user` pasa el type-check en `/after` y no en `/before`, porque `/after` se
registra sobre el valor que devolvió `.provide()`, y `/before` se registra sobre el
valor de antes.
`provide()` no ensancha retroactivamente el tipo de una `app` que ya tienes — devuelve
una nueva, con un tipo más amplio. Registrar cualquier cosa que necesite un valor
provisto tiene que pasar sobre ese valor devuelto, ya sea encadenando como en el
ejemplo de arriba o reasignando, por ejemplo `app = app.provide(...)` con `app`
declarada `let`. Llamar a `.provide()` y después seguir registrando rutas como
statements separados sobre el `const app` original no va a pasar el type-check,
aunque el valor esté presente en `ctx` en runtime de todas formas.
## Plano, sin namespace [#plano-sin-namespace]
Un valor provisto queda directo sobre `ctx` — no hay ningún objeto envoltorio que
atravesar:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.provide(() => ({ user: { id: 1, name: 'Alice' } }))
.get('/me', ctx => ctx.user)
app.listen()
```
## Keys reservadas [#keys-reservadas]
Una llamada a `provide()` no puede reusar una key que ya está ahí. Eso incluye los
campos base de `Context` — `request`, `params`, `query`, `response`, `body` — y
cualquier key que un `provide()` anterior en la cadena ya haya agregado. Ambos casos
se refuerzan a nivel de tipos: reusar una es un error de compilación.
Ver [Descripción general de Providers](./overview.mdx) para la mecánica request por
request, y [Context](../fundamentals/context.mdx) para los campos base junto a los
que queda un valor provisto.
# HTTP Methods (/es/docs/routing/http-methods)
Cada método HTTP tiene su propio método de registro:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.post('/users', () => ({ created: true }))
app.put('/users/:id', ctx => ({ replaced: ctx.params.id }))
app.patch('/users/:id', ctx => ({ updated: ctx.params.id }))
app.delete('/users/:id', ctx => ({ deleted: ctx.params.id }))
app.head('/users/:id', () => {})
app.options('/users', () => {})
app.listen()
```
Los siete disponibles son `get`, `post`, `put`, `delete`, `patch`, `head`
y `options`. Se comportan idénticos más allá del método que responden, y
todos aceptan las mismas dos formas de llamada — un handler con
[middleware de ruta](../middleware/route-level.mdx) opcional, o un
[objeto de opciones](../validation/overview.mdx) con schemas.
## Varios métodos en un mismo path [#varios-métodos-en-un-mismo-path]
Regístralos uno por uno. Como cada llamada retorna la app, un recurso se
lee como un bloque:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/users/:id', ctx => ({ id: ctx.params.id }))
.put('/users/:id', ctx => ({ replaced: ctx.params.id }))
.delete('/users/:id', ctx => ({ deleted: ctx.params.id }))
app.listen()
```
Registrar el mismo método y path dos veces tira un error al registrarse
— ver [Registration errors](../errors/registration-errors.mdx).
## Todos los métodos en un mismo path [#todos-los-métodos-en-un-mismo-path]
`app.all()` registra el mismo handler para los siete métodos anteriores en
una sola llamada. Sirve sobre todo para delegar un path completo — muchas
veces un subárbol wildcard — a un handler externo de Request/Response, por
ejemplo montar una librería como [better-auth](https://www.better-auth.com):
```ts
import { Arcton } from '@arcton/core'
declare const auth: { handler: (request: Request) => Promise }
const app = Arcton()
app.all('/api/auth/*path', ctx => auth.handler(ctx.request))
app.listen()
```
`all` no es un comodín para verbos HTTP arbitrarios o no estándar — expande
exactamente a los mismos siete métodos que responden `get`/`post`/etc. Un
request con otro verbo sigue recibiendo `405` (si el path matchea otra cosa)
o `404`.
Como comparte el mismo handler entre los siete métodos, registrar `all()` y
luego un método específico en el mismo path — en cualquier orden — tira el
mismo error de "Duplicate route" que registrar ese método dos veces; ver
[Registration errors](../errors/registration-errors.mdx). Y como cualquier
segmento wildcard, `/api/auth/*path` necesita al menos un segmento para
matchear — si necesitas que `/api/auth` a secas también responda, hace falta
registrarlo aparte.
## Method not allowed [#method-not-allowed]
Cuando el path de un request matchea pero su método no tiene handler,
Arcton responde `405` con un header `Allow` listando los métodos que ese
path sí responde:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.post('/users/:id', ctx => ({ updated: ctx.params.id }))
app.listen()
```
`DELETE /users/42` retorna `405` con `Allow: GET, POST` y el cuerpo
vacío.
El path que responde es el más específico que matcheó, y el matching no
sigue buscando más allá de él otro patrón que soporte el método —
[Precedence](./precedence.mdx) desarrolla las consecuencias de esto.
## HEAD y OPTIONS [#head-y-options]
Acá ambos son métodos ordinarios: responden cuando los registras.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.head('/users/:id', ctx => {
ctx.response.headers.set('Content-Type', 'application/json')
})
app.options('/users/:id', ctx => {
ctx.response.status = 204
ctx.response.headers.set('Allow', 'GET, HEAD, OPTIONS')
})
app.listen()
```
Para requests de preflight cross-origin,
[`@arcton/cors`](../middleware/cors.mdx) maneja el intercambio de
`OPTIONS` por ti, y solo intercepta requests que llevan
`Access-Control-Request-Method` — así que una ruta `app.options()` que
registres para tus propios fines sigue funcionando junto a él.
## Elegir un status code [#elegir-un-status-code]
Un handler responde `200` a menos que digas lo contrario. Asigna
`ctx.response.status` antes de retornar:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/users', ctx => {
ctx.response.status = 201
ctx.response.headers.set('Location', '/users/42')
return { id: '42' }
})
app.delete('/users/:id', ctx => {
ctx.response.status = 204
})
app.listen()
```
`204`, `205` y `304` siempre envían el cuerpo vacío, sea lo que sea que
retorne el handler. Ver [Response](../fundamentals/response.mdx).
# Modules (/es/docs/routing/modules)
Un módulo es una instancia de `Arcton()` con un prefix. Montarlo con
`use()` fusiona sus rutas en el padre:
```ts title="users.ts"
import { Arcton } from '@arcton/core'
export const users = Arcton({ prefix: '/users' })
users.get('/', () => [{ id: '1' }])
users.get('/:id', ctx => ({ id: ctx.params.id }))
users.post('/', () => ({ created: true }))
```
```ts title="index.ts"
import { Arcton } from '@arcton/core'
import { users } from './users'
const app = Arcton({ prefix: '/api' })
app.use(users)
app.listen()
```
Eso sirve `GET /api/users`, `GET /api/users/:id` y `POST /api/users`.
Un módulo no es un tipo especial. Es una aplicación — los mismos
métodos, el mismo middleware, la misma validation. Lo que lo convierte
en un módulo es que otra cosa lo monta.
## Los prefixes se componen [#los-prefixes-se-componen]
El path donde termina una ruta es el prefix del padre, después el
prefix del módulo, después el path de la ruta:
```text
'/api' + '/users' + '/:id' → /api/users/:id
```
Un prefix debe ser un path static; los segmentos `:param` y `*wildcard`
tiran un error cuando se crea la instancia. `Arcton({ prefix: '/' })` es
lo mismo que no tener prefix.
## Montar fusiona el árbol de rutas [#montar-fusiona-el-árbol-de-rutas]
`app.use(module)` copia las rutas del módulo en el árbol de rutas del
padre en el momento en que lo llamas. Después de montar hay un solo
árbol, y un request cuesta una sola búsqueda sin importar de cuántos
módulos se armó la aplicación.
De fusionar en tiempo de registro se siguen dos consecuencias:
* Las rutas registradas en el módulo **después** de haber sido montado
no aparecen en el padre. Monta un módulo una vez que ya está
completamente construido — típicamente como lo último que hace el
archivo del padre.
* Una colisión sale a la luz de inmediato. Si montar produjera un método
y path que el padre ya tiene, el registro tira un error, igual que
registrar una ruta duplicada directamente.
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.use(users) // throws: Duplicate route: GET /users/:id is already registered
app.listen()
```
## Middleware y montaje [#middleware-y-montaje]
El middleware global y los providers del padre registrados **antes**
del montaje envuelven cada ruta que trae el módulo. Cualquier cosa
registrada después no lo alcanza — la misma regla de orden de registro
que gobierna al [middleware](../middleware/execution-order.mdx) en
todos lados.
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
const app = Arcton()
app.use(async (ctx, next) => {
await next()
ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
})
app.use(users) // every route the module brings in gets the header
app.listen()
```
Cada instancia se tipa por su cuenta, así que los handlers de un módulo
ven el contexto que ese módulo declara. Cuando los handlers de un
módulo necesitan un valor tipado, es el módulo el que declara el
provider:
```ts
import { Arcton } from '@arcton/core'
const users = Arcton({ prefix: '/users' })
users
.provide(ctx => ({
requestId: ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()
}))
.get('/:id', ctx => ({ id: ctx.params.id, requestId: ctx.requestId }))
const app = Arcton()
app.use(users)
app.listen()
```
Un módulo también conserva su propio middleware, incluyendo el
middleware con scope de path, que sigue comparándose contra el path
módulo-local — el path tal como se escribió adentro del módulo, no el
ya montado:
```ts
import { Arcton } from '@arcton/core'
const api = Arcton({ prefix: '/api' })
api.use('/admin', async (ctx, next) => {
if (ctx.request.headers.get('x-admin-key') !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
await next()
})
api.get('/admin/stats', () => ({ users: 1 }))
api.get('/public', () => ({ ok: true }))
const app = Arcton()
app.use(api)
app.listen()
```
El scope se escribe `'/admin'`, coincidiendo con la ruta tal como se
escribió adentro del módulo, mientras que la ruta se sirve en
`/api/admin/stats`.
El middleware con scope de path del padre no alcanza a un módulo
montado. Pon el middleware con scope adentro del módulo al que
pertenece, o usa middleware global en el padre.
## Anidamiento [#anidamiento]
Los módulos montan módulos, a cualquier profundidad:
```ts
import { Arcton } from '@arcton/core'
const posts = Arcton({ prefix: '/posts' })
posts.get('/:postId', ctx => ({ post: ctx.params.postId }))
const users = Arcton({ prefix: '/users' })
users.get('/:id', ctx => ({ id: ctx.params.id }))
users.use(posts)
const app = Arcton({ prefix: '/api' })
app.use(users)
app.listen()
```
Esto sirve `GET /api/users/:id` y `GET /api/users/posts/:postId`.
## Las rutas WebSocket también viajan [#las-rutas-websocket-también-viajan]
Una [ruta WebSocket](./websockets.mdx) registrada adentro de un módulo
recibe ambos prefixes al montarse:
```ts
import { Arcton } from '@arcton/core'
const chat = Arcton({ prefix: '/chat' })
chat.ws('/room', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
const app = Arcton({ prefix: '/api' })
app.use(chat)
app.listen()
```
El socket se sirve en `/api/chat/room`.
## Organizar una aplicación real [#organizar-una-aplicación-real]
Un layout común es un módulo por dominio, cada uno dueño de sus rutas y
del middleware que necesita:
```text
src/
├── index.ts # crea la app, monta los módulos, llama a listen()
├── users/
│ └── index.ts # export const users = Arcton({ prefix: '/users' })
└── orders/
└── index.ts # export const orders = Arcton({ prefix: '/orders' })
```
```ts title="src/index.ts" no-check
import { Arcton } from '@arcton/core'
import { orders } from './orders'
import { users } from './users'
const app = Arcton({ prefix: '/api' })
app.use(async (ctx, next) => {
console.log(`${ctx.request.method} ${new URL(ctx.request.url).pathname}`)
await next()
})
app.use(users)
app.use(orders)
app.listen({ port: 3000 })
```
El middleware de logging se registra antes de los montajes, así que
cubre todas las rutas que traen ambos módulos.
Ver [Module composition](../architecture/module-composition.mdx) para
saber por qué la fusión ocurre en tiempo de registro.
# Routing Overview (/es/docs/routing/overview)
Registra una ruta llamando al método que quieres que responda:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users', () => [{ id: '1' }])
app.post('/users', () => ({ created: true }))
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
Cada método de registro retorna la app, así que las llamadas se encadenan:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app
.get('/health', () => ({ status: 'ok' }))
.get('/version', () => ({ version: '1.0.0' }))
app.listen()
```
Hay siete métodos disponibles: `get`, `post`, `put`, `delete`, `patch`,
`head` y `options`. Ver [HTTP methods](./http-methods.mdx).
## Tres tipos de segmento [#tres-tipos-de-segmento]
Un path se divide por `/`, y cada segmento es uno de tres tipos:
| Segmento | Se escribe | Matchea |
| -------- | ---------- | ----------------------------------------------------------- |
| Static | `users` | exactamente ese texto |
| Dynamic | `:id` | un solo segmento cualquiera, capturado como `ctx.params.id` |
| Wildcard | `*path` | el resto del path, capturado como `ctx.params.path` |
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/health', () => ({ status: 'ok' })) // static
app.get('/users/:id', ctx => ({ id: ctx.params.id })) // dynamic
app.get('/files/*path', ctx => ({ path: ctx.params.path })) // wildcard
app.listen()
```
`GET /files/docs/readme.md` da `ctx.params.path === 'docs/readme.md'`.
Los valores capturados están tipados a partir del path que escribiste —
ver [Path parameters](./path-parameters.mdx). Cuando más de una ruta
podría matchear un request, [Precedence](./precedence.mdx) decide.
## Reglas para el path de una ruta [#reglas-para-el-path-de-una-ruta]
Estas se verifican cuando la ruta se registra, así que un error tira al
arrancar en vez de aparecer como sorpresa más adelante.
* Un path debe empezar con `/`.
* Un path no puede contener `//`.
* Un nombre de parámetro debe empezar con una letra y contener solo
letras, dígitos y `_`.
* Un wildcard debe ser el último segmento.
* El mismo nombre de parámetro no puede aparecer dos veces en un mismo
path.
* El mismo método y path no pueden registrarse dos veces.
* Dos rutas no pueden usar nombres de parámetro distintos en el mismo
slot en la misma posición — `'/users/:id'` y `'/users/:userId'` entran
en conflicto.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.get('/users/:id/posts', ctx => ({ user: ctx.params.id })) // same name, fine
app.listen()
```
Los mensajes exactos están listados en
[Registration errors](../errors/registration-errors.mdx).
## Slashes finales [#slashes-finales]
Los segmentos vacíos se descartan antes de matchear, así que un slash
final y uno repetido resuelven a la misma ruta:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'me')
app.listen()
```
`GET /users/me`, `GET /users/me/` y `GET /users//me` llegan todos al
mismo handler.
## Handlers [#handlers]
Un handler recibe el [context](../fundamentals/context.mdx) y retorna el
cuerpo de la respuesta. Puede ser sync o async:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/sync', () => ({ ok: true }))
app.get('/async', async () => {
const data = await Promise.resolve({ ok: true })
return data
})
app.listen()
```
La desestructuración funciona cuando solo necesitas parte del contexto:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ({ params }) => ({ id: params.id }))
app.listen()
```
## Más allá de un solo archivo [#más-allá-de-un-solo-archivo]
Las rutas pueden llevar su propio
[middleware](../middleware/route-level.mdx) y
[schemas de validation](../validation/overview.mdx), y una aplicación
puede dividirse en [módulos](./modules.mdx) que se fusionan en un único
árbol de rutas.
# Path Parameters (/es/docs/routing/path-parameters)
Un segmento `:name` captura un segmento de path:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.listen()
```
`GET /users/42` retorna `{"id":"42"}`.
## Los tipos vienen del path [#los-tipos-vienen-del-path]
Arcton lee el literal de la ruta y tipa `ctx.params` a partir de él. No
hay ningún argumento genérico involucrado:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/orgs/:orgId/repos/:repoId', ctx => {
// ctx.params is { orgId: string; repoId: string }
return { org: ctx.params.orgId, repo: ctx.params.repoId }
})
app.listen()
```
Leer un nombre que el path no declara es un error de compilación. Una
ruta sin parámetros no tiene ninguna key de parámetro para leer.
La inferencia necesita un literal. Si el path viene de una variable
tipada como `string`, `ctx.params` cae a `Record`. Pasar
el path en línea mantiene el tipo preciso.
## Los valores de parámetro son strings [#los-valores-de-parámetro-son-strings]
Cada valor capturado es un string, porque eso es lo que lleva una URL.
Para trabajar con un número, conviértelo — o declara un schema y deja que
la validation produzca el valor convertido:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/users/:id', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
handler: ctx => ({ id: ctx.params.id, type: typeof ctx.params.id })
})
app.listen()
```
`GET /users/42` ahora retorna `{"id":42,"type":"number"}`. Ver
[Params and query](../validation/params-and-query.mdx).
## Wildcards [#wildcards]
Un segmento `*name` captura todo lo que queda del path, unido con `/`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/files/*path', ctx => ({ path: ctx.params.path }))
app.listen()
```
| Request | `ctx.params.path` |
| ---------------------------- | --------------------- |
| `/files/readme.md` | `readme.md` |
| `/files/docs/api/index.html` | `docs/api/index.html` |
Un wildcard debe ser el último segmento del path, y necesita al menos un
segmento para matchear: con solo `/files/*path` registrado, `GET /files`
y `GET /files/` producen un `404`. Registra `/files` por separado si
quieres responderla.
Como un wildcard acepta cualquier resto del path, valida el valor
capturado antes de usarlo para acceder a algo en disco:
```ts
import { Arcton } from '@arcton/core'
const files: Record = {
'readme.md': '# Arcton',
'docs/intro.md': 'Welcome'
}
const app = Arcton()
app.get('/files/*path', ctx => {
const segments = ctx.params.path.split('/')
if (segments.some(segment => segment === '..' || segment === '')) {
return new Response('Invalid path', { status: 400 })
}
const content = files[ctx.params.path]
if (content === undefined) {
return new Response('Not found', { status: 404 })
}
return new Response(content, { headers: { 'content-type': 'text/plain' } })
})
app.listen()
```
## Valores percent-encoded [#valores-percent-encoded]
Los valores capturados se decodean con percent-decoding; las partes
estáticas del path se matchean tal como están escritas.
`GET /users/hello%20world` da `ctx.params.id === 'hello world'`. Un valor
cuya secuencia de escape es inválida se te entrega exactamente como llegó
en vez de fallar el request.
## Múltiples parámetros [#múltiples-parámetros]
Cualquier cantidad de segmentos dinámicos puede aparecer en un path,
mientras sus nombres difieran:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/:year/:month/:slug', ctx => ({
year: ctx.params.year,
month: ctx.params.month,
slug: ctx.params.slug
}))
app.listen()
```
Un segmento dinámico y uno wildcard también pueden compartir un path,
con el wildcard al final:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id/files/*path', ctx => ({
user: ctx.params.id,
path: ctx.params.path
}))
app.listen()
```
## Misma posición, mismo nombre [#misma-posición-mismo-nombre]
Las rutas que comparten un prefix deben coincidir en el nombre del
parámetro en cada posición:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/:id', ctx => ({ id: ctx.params.id }))
app.get('/users/:id/posts', ctx => ({ user: ctx.params.id }))
app.listen()
```
Escribir `'/users/:userId/posts'` junto con `'/users/:id'` tira un error
al registrarse, porque una posición capturaría bajo dos nombres
distintos. Ver [Registration errors](../errors/registration-errors.mdx).
# Route Precedence (/es/docs/routing/precedence)
Cuando más de una ruta podría matchear un request, Arcton sigue dos
reglas: **static gana a dynamic gana a wildcard**, aplicadas un segmento
a la vez, con backtracking cuando una rama llega a un callejón sin
salida.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'the current user')
app.get('/users/:id', ctx => `user ${ctx.params.id}`)
app.get('/users/*path', ctx => `anything else: ${ctx.params.path}`)
app.listen()
```
| Request | Gana | Por qué |
| ------------------ | -------------- | ------------------------------------------------------- |
| `GET /users/me` | `/users/me` | primero se prueba un segmento static |
| `GET /users/42` | `/users/:id` | no hay static `42`, así que se lo lleva el slot dynamic |
| `GET /users/a/b/c` | `/users/*path` | más segmentos de los que `:id` puede contener |
El orden de registro no importa. Mover `/users/me` al final del archivo
no cambia nada — la precedencia es una propiedad del path, no de cuándo
lo escribiste.
## El matching recorre el path [#el-matching-recorre-el-path]
Arcton guarda las rutas en un árbol, un nodo por segmento. En cada nodo
prueba primero el hijo static, después el slot dynamic, después el slot
wildcard.
Para `GET /users/42` contra las rutas de arriba:
```text
/users/42
├─ "users" → existe un hijo static ✓ desciende
└─ "42" → ¿hijo static "me"? ✗
¿slot dynamic ":id"? ✓ captura id="42", desciende
el nodo tiene un handler GET ✓ match
```
## Backtracking [#backtracking]
Si una rama matchea por un tiempo y después llega a un callejón sin
salida, Arcton retrocede y prueba el siguiente slot en el punto donde
todavía tenía opciones, descartando los parámetros que esa rama
abandonada haya capturado.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/a/:b/c', ctx => `deep: ${ctx.params.b}`)
app.get('/a/*rest', ctx => `rest: ${ctx.params.rest}`)
app.listen()
```
| Request | Resultado |
| ------------ | ---------------------------------------------------------------------------- |
| `GET /a/x/c` | `deep: x` — la rama dynamic llega hasta `c` y matchea |
| `GET /a/x/y` | `rest: x/y` — `y` no es `c`, así que el matching retrocede hacia el wildcard |
La `b` capturada al entrar en la rama abandonada se descarta, así que el
handler que finalmente corre nunca ve un parámetro de un path que no
matcheó.
## Un método que no coincide termina la búsqueda [#un-método-que-no-coincide-termina-la-búsqueda]
El backtracking aplica a *paths*, no a métodos. Una vez que el matching
llega a un nodo que tiene handlers, ese nodo responde — con el handler
para este método si lo tiene, y con `405` si no lo tiene. Arcton no
sigue buscando otro patrón de path que resulte soportar el método.
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'the current user')
app.post('/users/:id', ctx => `updated ${ctx.params.id}`)
app.listen()
```
| Request | Respuesta |
| ---------------- | ---------------------- |
| `GET /users/me` | `200` |
| `POST /users/42` | `200` |
| `POST /users/me` | `405` con `Allow: GET` |
`POST /users/me` llega al nodo `/users/me`, que solo responde `GET`, así
que retorna `405` — aunque `/users/:id` hubiera aceptado el `POST`.
El path más específico que matchea es el que responde. Si un path
static debería aceptar los mismos métodos que la ruta dynamic de al
lado, registra esos métodos también en el path static.
Haciendo que el ejemplo de arriba responda a ambos:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/users/me', () => 'the current user')
app.post('/users/me', () => 'updated the current user')
app.post('/users/:id', ctx => `updated ${ctx.params.id}`)
app.listen()
```
## Ningún match [#ningún-match]
Cuando ningún path del árbol matchea, la respuesta es `404` con un body
JSON `{ code: 'NOT_FOUND', message: 'Not Found' }` — ver
[HTTP errors](../api/http-errors.mdx). El middleware global igual corre
sobre ella, que es como los headers de logging y CORS llegan a esas
respuestas — ver [Global middleware](../middleware/global.mdx).
## Los wildcards necesitan algo que capturar [#los-wildcards-necesitan-algo-que-capturar]
Un wildcard matchea uno o más segmentos, nunca cero:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/files', () => 'the index')
app.get('/files/*path', ctx => `file: ${ctx.params.path}`)
app.listen()
```
Sin esa primera ruta, `GET /files` sería un `404`, porque `*path` no
tiene nada que capturar.
# Query Parameters (/es/docs/routing/query-parameters)
Los query parameters llegan en `ctx.query`:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/search', ctx => ({
term: ctx.query.q,
page: ctx.query.page
}))
app.listen()
```
`GET /search?q=arcton&page=2` retorna `{"term":"arcton","page":"2"}`.
## Los valores son strings, y pueden faltar [#los-valores-son-strings-y-pueden-faltar]
`ctx.query` es un `Record`. Una key que no se envió es
`undefined`, así que maneja la ausencia explícitamente:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/search', ctx => {
const term = ctx.query.q ?? ''
const page = Number(ctx.query.page ?? '1')
return { term, page }
})
app.listen()
```
Dos detalles que vale la pena conocer:
* Una key enviada sin valor es un string vacío: `?debug` da
`ctx.query.debug === ''`.
* Una key enviada más de una vez conserva el último valor: `?tag=a&tag=b`
da `ctx.query.tag === 'b'`.
El query string se parsea la primera vez que algo lee `ctx.query`, así
que un handler que nunca lo toca no paga nada por eso.
## Validar y convertir [#validar-y-convertir]
Convertir a mano se vuelve repetitivo apenas una ruta toma más de un
parámetro. Un schema de `query` hace la conversión y el tipado en un solo
lugar:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/search', {
query: v.object({
q: v.string(),
page: v.optional(
v.pipe(v.string(), v.transform(Number), v.number()),
'1'
)
}),
handler: ctx => ({ term: ctx.query.q, page: ctx.query.page })
})
app.listen()
```
`ctx.query.page` aquí es un `number`, y un request al que le falta `q` se
responde con `400` antes de que el handler corra. Ver
[Params and query](../validation/params-and-query.mdx) y
[Validation errors](../validation/validation-errors.mdx).
## Leer el query string crudo [#leer-el-query-string-crudo]
`ctx.request.url` siempre está disponible cuando necesitas la URL en sí
— para keys repetidas que quieres conservar, por ejemplo:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/filter', ctx => {
const url = new URL(ctx.request.url)
const tags = url.searchParams.getAll('tag')
return { tags }
})
app.listen()
```
`GET /filter?tag=a&tag=b` retorna `{"tags":["a","b"]}`.
Los query parameters no son parte del matching de rutas. `/search` y
`/search?q=x` llegan a la misma ruta, y dos rutas no pueden
distinguirse por su query string.
# WebSockets (/es/docs/routing/websockets)
`app.ws()` registra una ruta WebSocket en el mismo servidor que tus
rutas HTTP:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/', () => ({ ok: true }))
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
app.listen({ port: 3000 })
```
Un cliente que se conecta a `ws://localhost:3000/chat` recibe el upgrade
automáticamente. Todo lo demás en el servidor sigue funcionando sobre
HTTP.
## El handler [#el-handler]
`message` es el único callback requerido. `open`, `close` y `drain` son
opcionales:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
open(ws) {
ws.send('connected')
},
message(ws, message) {
ws.send(`echo: ${message}`)
},
close(ws, code, reason) {
console.log('closed', code, reason)
},
drain(ws) {
console.log('socket ready for more data')
}
})
app.listen()
```
| Callback | Se llama cuando |
| ------------------------- | ---------------------------------------------------------------- |
| `message(ws, message)` | llega un frame — `string` para texto, `ArrayBuffer` para binario |
| `open(ws)` | la conexión quedó establecida |
| `close(ws, code, reason)` | la conexión se cerró |
| `drain(ws)` | un socket con backpressure puede aceptar más datos |
Cada callback puede ser async.
## El socket [#el-socket]
El valor `ws` que se pasa a cada callback ofrece dos métodos:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
if (message === 'bye') {
ws.close(1000, 'client said bye')
return
}
ws.send(`echo: ${message}`)
}
})
app.listen()
```
`send()` acepta un string, un `ArrayBuffer` o un typed array. `close()`
toma un código y una razón opcionales.
## Frames de texto y binarios [#frames-de-texto-y-binarios]
`message` es un `string` para frames de texto y un `ArrayBuffer` para
binarios, así que haz el narrowing antes de usarlo:
```ts
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/upload', {
message(ws, message) {
if (typeof message === 'string') {
ws.send(`text of length ${message.length}`)
return
}
ws.send(`binary of ${message.byteLength} bytes`)
}
})
app.listen()
```
## Sockets en módulos [#sockets-en-módulos]
Una ruta WebSocket registrada adentro de un [módulo](./modules.mdx)
recibe los prefixes cuando se monta:
```ts
import { Arcton } from '@arcton/core'
const chat = Arcton({ prefix: '/chat' })
chat.ws('/room', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
const app = Arcton({ prefix: '/api' })
app.use(chat)
app.listen()
```
El socket se sirve en `/api/chat/room`.
## Soporte de runtime [#soporte-de-runtime]
Las rutas WebSocket necesitan un adapter que las soporte; tanto el de
Bun como el de Node.js lo hacen. La verificación ocurre cuando llamas a
`listen()`, no cuando registras la ruta — montar un módulo todavía puede
agregar rutas WebSocket después de una llamada a `ws()`, así que
`listen()` es el primer momento en que se conoce el conjunto completo.
```ts
import { nodeAdapter } from '@arcton/adapter-node'
import { Arcton } from '@arcton/core'
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
app.listen({ adapter: nodeAdapter })
```
## En qué se diferencian las rutas ws de las rutas HTTP [#en-qué-se-diferencian-las-rutas-ws-de-las-rutas-http]
Las rutas WebSocket se matchean por path exacto — los segmentos
`:param` y `*wildcard` pertenecen a las rutas HTTP. También las sirve
directamente el adapter en vez del pipeline HTTP, así que una conexión
de socket no corre [middleware](../middleware/overview.mdx),
[providers](../providers/overview.mdx) ni
[validation](../validation/overview.mdx), y los callbacks reciben el
socket en vez de un [context](../fundamentals/context.mdx).
Para controlar el acceso a una conexión, verifica adentro de `open` y
cierra el socket cuando la verificación falle:
```ts
import { Arcton } from '@arcton/core'
const rooms = new Set(['general', 'random'])
const app = Arcton()
app.ws('/room', {
open(ws) {
ws.send('joined')
},
message(ws, message) {
const room = String(message)
if (!rooms.has(room)) {
ws.close(1008, 'unknown room')
return
}
ws.send(`welcome to ${room}`)
}
})
app.listen()
```
## Conectarse desde un cliente [#conectarse-desde-un-cliente]
```ts
const socket = new WebSocket('ws://localhost:3000/chat')
socket.addEventListener('open', () => {
socket.send('hello')
})
socket.addEventListener('message', event => {
console.log(event.data)
})
```
# Pruebas (/es/docs/testing/overview)
Las apps de Arcton se testean con [`bun:test`](https://bun.sh/docs/cli/test), el mismo runner que usa el propio framework. No hay un test client separado ni una capa de mocking que aprender: se ejercita la app real.
## Dos técnicas [#dos-técnicas]
* **Rutas** — levantar un servidor real en un puerto efímero con `app.listen({ port: 0 })`, golpearlo con el `fetch` de la plataforma y luego llamar a `server.stop()`. Esto corre el pipeline completo (middleware, providers, validación, el handler) exactamente como corre en producción. Ver [Testing routes](./testing-routes.mdx).
* **Middleware** — un [`Middleware`](../api/middleware-types.mdx) es una simple función `(ctx, next) => ...`, así que puede llamarse directamente con un `ctx` armado a mano y un `next` falso, sin ningún servidor de por medio. Ver [Testing middleware](./testing-middleware.mdx).
La primera técnica sirve para confirmar el comportamiento de punta a punta (routing, status codes, headers, cuerpos de respuesta). La segunda sirve para testear una pieza de middleware de forma aislada, independiente de cualquier ruta en particular.
# Testing de middleware (/es/docs/testing/testing-middleware)
Un [`Middleware`](../api/middleware-types.mdx) no es más que una función `(ctx, next) => ...`. Eso significa que se puede testear directamente, sin servidor ni ruta: se arma un `ctx` mínimo a mano, se le pasa un `next` falso, y se verifica qué hizo el middleware.
## Un helper `makeCtx` [#un-helper-makectx]
```ts
import type { Context } from '@arcton/contracts'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
```
Esto construye el `Context` mínimo que necesita un middleware: el `request` entrante, `params`/`query` vacíos, y un `response` nuevo con `Headers` vacíos. Se puede reutilizar para cualquier middleware bajo test, no solo uno específico de tu app.
## Testeando un middleware que llama a `next()` [#testeando-un-middleware-que-llama-a-next]
```ts
import { expect, test } from 'bun:test'
import type { Context } from '@arcton/contracts'
import { cors } from '@arcton/cors'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
test('cors adds Access-Control-Allow-Origin for an allowed origin', async () => {
const middleware = cors({ origin: 'https://app.example.com' })
const ctx = makeCtx(
new Request('http://localhost/', {
headers: { origin: 'https://app.example.com' }
})
)
await middleware(ctx, async () => {})
expect(ctx.response.headers.get('Access-Control-Allow-Origin')).toBe(
'https://app.example.com'
)
})
```
## Testeando un middleware que corta la cadena [#testeando-un-middleware-que-corta-la-cadena]
Un middleware que devuelve un valor sin llamar a `next()` corta la cadena del pipeline. Hay que verificar que `next` nunca se llamó e inspeccionar el valor devuelto directamente:
```ts
import { expect, test } from 'bun:test'
import type { Context } from '@arcton/contracts'
import { cors } from '@arcton/cors'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
test('a real preflight short-circuits with a 204 Response', async () => {
const middleware = cors({ origin: 'https://app.example.com' })
const ctx = makeCtx(
new Request('http://localhost/users', {
method: 'OPTIONS',
headers: {
origin: 'https://app.example.com',
'access-control-request-method': 'POST'
}
})
)
let nextCalled = false
const result = await middleware(ctx, async () => {
nextCalled = true
})
expect(nextCalled).toBe(false)
expect(result).toBeInstanceOf(Response)
expect((result as Response).status).toBe(204)
})
```
## Testeando tu propio middleware [#testeando-tu-propio-middleware]
La misma técnica aplica a cualquier middleware que escribas, no solo a uno incluido en el framework:
```ts
import { expect, test } from 'bun:test'
import type { Context, Middleware } from '@arcton/contracts'
function makeCtx(request: Request): Context {
return {
request,
params: {},
query: {},
response: { headers: new Headers() }
}
}
const withRequestId: Middleware = async (ctx, next) => {
ctx.response.headers.set('X-Request-Id', 'test-id')
await next()
}
test('withRequestId sets a header before calling next', async () => {
const ctx = makeCtx(new Request('http://localhost/'))
let nextCalled = false
await withRequestId(ctx, async () => {
nextCalled = true
})
expect(nextCalled).toBe(true)
expect(ctx.response.headers.get('X-Request-Id')).toBe('test-id')
})
```
`Context` se importa como tipo desde `@arcton/contracts`. Esto testea la función de middleware de forma aislada, desacoplada del routing y del resto del pipeline — para un test de punta a punta que corre un middleware como parte de un request real, ver [Testing routes](./testing-routes.mdx).
# Testing de rutas (/es/docs/testing/testing-routes)
La forma confiable de testear una ruta es levantar la app real en un puerto real (efímero) y golpearla con una llamada `fetch` real. Nada está mockeado: el matching, el middleware, los providers, la validación y el handler corren exactamente como lo harían en producción.
## La forma básica [#la-forma-básica]
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
test('GET /health returns ok', async () => {
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
const server = app.listen({ port: 0 })
const res = await fetch(new URL('/health', server.url))
expect(await res.json()).toEqual({ status: 'ok' })
server.stop()
})
```
`port: 0` le pide al runtime un puerto libre en lugar de uno fijo, así los tests pueden correr en paralelo sin chocar. `server.url` es una `URL` real: se puede pasar directamente a `fetch`, o resolver una ruta contra ella con `new URL(path, server.url)`. Siempre hay que llamar a `server.stop()` al terminar el test para liberar el puerto.
## Testeando un 404 [#testeando-un-404]
Una ruta sin match responde `404` con un body JSON `{ code: 'NOT_FOUND', message: 'Not Found' }` (ver [HTTP errors](../api/http-errors.mdx)) — vale la pena verificarlo directamente:
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
test('an unmatched path responds 404', async () => {
const app = Arcton()
app.get('/health', () => ({ status: 'ok' }))
const server = app.listen({ port: 0 })
const res = await fetch(new URL('/missing', server.url))
expect(res.status).toBe(404)
server.stop()
})
```
## Testeando la validación [#testeando-la-validación]
Una ruta con un schema de `body`, `query` o `params` responde `400` con un cuerpo JSON `{ issues: [...] }` en la primera falla de validación. Este ejemplo usa [Valibot](https://valibot.dev):
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
test('an invalid body responds 400 with issues', async () => {
const app = Arcton()
app.post('/orders', {
body: v.object({ item: v.string(), quantity: v.number() }),
handler: ctx => ctx.body
})
const server = app.listen({ port: 0 })
const res = await fetch(new URL('/orders', server.url), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ item: 'widget' })
})
expect(res.status).toBe(400)
const body = (await res.json()) as { issues: { message: string }[] }
expect(Array.isArray(body.issues)).toBe(true)
server.stop()
})
```
## Testeando una ruta WebSocket [#testeando-una-ruta-websocket]
El mismo servidor de `app.listen({ port: 0 })` también sirve las [rutas WebSocket](../routing/websockets.mdx) registradas. Hay que abrir un `WebSocket` contra `server.url` cambiando el protocolo a `ws:`:
```ts
import { expect, test } from 'bun:test'
import { Arcton } from '@arcton/core'
test('a ws route echoes messages', async () => {
const app = Arcton()
app.ws('/chat', {
message(ws, message) {
ws.send(`echo: ${message}`)
}
})
const server = app.listen({ port: 0 })
const wsUrl = new URL('/chat', server.url)
wsUrl.protocol = 'ws:'
const ws = new WebSocket(wsUrl)
await new Promise(resolve => {
ws.addEventListener('open', () => resolve())
})
const reply = new Promise(resolve => {
ws.addEventListener('message', event => resolve(event.data as string))
})
ws.send('hi')
expect(await reply).toBe('echo: hi')
ws.close()
server.stop()
})
```
Para testear una pieza de middleware por su cuenta, sin correr ningún servidor, ver [Testing middleware](./testing-middleware.mdx).
# Parsers de Body (/es/docs/validation/body-parsers)
El parseo de body solo pasa para una ruta que declaró un esquema de `body` — ver
[Body](./body.mdx). Arcton elige un parser según el `Content-Type` de la request
(los parámetros como `; charset=` se ignoran, y la comparación no distingue mayúsculas
de minúsculas), lo ejecuta, y le entrega el resultado a tu esquema. Una ruta
acepta únicamente `application/json` por defecto; cualquier otro media type hay
que listarlo con `content` — ver
[Aceptar media types específicos](./body.mdx#accepting-specific-media-types).
## Parsers integrados [#parsers-integrados]
Estos son los parsers que trae Arcton. Una ruta solo recibe un media type que
acepta: `application/json` por defecto, o los que lista en `content`.
| Content-Type | Valor parseado |
| --------------------------------------------------- | ---------------------- |
| `application/json` y cualquier `application/*+json` | `await request.json()` |
| `text/plain` | `string` |
| `application/x-www-form-urlencoded` | `FormData` |
| `multipart/form-data` | `FormData` |
| `application/octet-stream` | `ArrayBuffer` |
Una request cuyo `Content-Type` la ruta no acepta — o que no tiene parser, integrado
o personalizado — recibe `415` con un body vacío. Un parser integrado que
lanza un error con un input malformado (JSON inválido, por ejemplo) responde `400`
con `{"issues":[{"message":"Invalid request body"}]}`. Una request sin body
nunca llega a un parser cuando el body de la ruta es
[opcional](./body.mdx#optional-bodies).
## Registrando tu propio parser [#registrando-tu-propio-parser]
`app.parser(mediaType, parser)` registra un parser para un media type exacto,
sobrescribiendo uno integrado para el mismo tipo si existe. Registrar el mismo media
type de nuevo reemplaza el parser anterior — es una tabla plana, no un pipeline
ordenado, así que no importa en qué momento lo llames respecto a tus rutas.
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.parser('text/csv', async request => {
const [header = '', ...rows] = (await request.text()).trim().split('\n')
const keys = header.split(',')
return rows.map(row =>
Object.fromEntries(keys.map((key, i) => [key, row.split(',')[i]]))
)
})
app.post('/import', {
body: {
content: { 'text/csv': v.array(v.record(v.string(), v.string())) }
},
handler: ctx => ({ imported: ctx.body.length, rows: ctx.body })
})
app.listen()
```
Un `BodyParser` recibe el `Request` crudo, no `ctx` — el parseo no tiene nada que ver
con el context de la ruta.
Devolver `undefined` desde un parser personalizado significa "no manejo esta
request" y cae en `415`, igual que si no hubiera ningún parser registrado. Cualquier
otro valor cuenta como manejado, incluyendo `false`, `0` y `''`. Un parser
personalizado que lanza un error se propaga sin capturar, igual que si lo lanzara un
handler o `provide()` — no se atrapa en un `400` como sí pasa con el error de un
parser integrado.
# Body (/es/docs/validation/body)
Declarar un esquema de `body` en las opciones de una ruta te da `ctx.body` — el body
de la request, parseado según su `Content-Type` y validado contra tu esquema:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({
name: v.pipe(v.string(), v.minLength(1)),
email: v.pipe(v.string(), v.email())
}),
handler: ctx => ({ created: ctx.body })
})
app.listen()
```
`ctx.body` solo aparece — y solo pasa el type-check — en una ruta que declaró un
esquema de `body` de esta forma. Una ruta sin uno directamente no tiene `ctx.body`.
## Body no es solo JSON [#body-no-es-solo-json]
Una ruta acepta `application/json` y nada más por defecto. Cualquier otro media
type — `text/plain`, un body de formulario, incluso un subtipo `+json` como
`application/vnd.api+json` — responde `415` antes de parsear nada, a menos que la
ruta lo declare explícitamente con
[`content`](#accepting-specific-media-types). El esquema valida contra el valor al
que ese media type parsee, así que una ruta puede recibir texto plano:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/notes', {
body: { content: { 'text/plain': v.pipe(v.string(), v.minLength(1)) } },
handler: ctx => ({ length: ctx.body.length })
})
app.listen()
```
o describir un body de `FormData`:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/upload', {
body: { content: { 'multipart/form-data': v.instance(FormData) } },
handler: ctx => ({ received: ctx.body.get('name') })
})
app.listen()
```
Qué valores de `Content-Type` parsean a qué valor de JavaScript — y qué pasa cuando
el `Content-Type` de la request no es uno que Arcton sepa parsear — está cubierto en
[Parsers de Body](./body-parsers.mdx).
## Bodies opcionales [#bodies-opcionales]
Un `body` es obligatorio por defecto: una request sin body se rechaza antes de
que corra tu schema. Para aceptarla también, pasa `{ schema, optional: true }`
en lugar de un schema pelado:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/reviews/:id/dismiss', {
body: {
schema: v.object({ reason: v.optional(v.string()) }),
optional: true
},
handler: ctx => ({ dismissedWith: ctx.body?.reason ?? null })
})
app.listen()
```
Una request que no trae body se salta el parseo y la validación, y `ctx.body`
es `undefined` — no se convierte en `{}`, y el schema nunca lo ve. El tipo lo
refleja: `ctx.body` es la salida del schema o `undefined`. Una request que sí
trae body se trata exactamente igual que antes: `{}` pasa por el schema, un JSON
malformado sigue siendo `400`, un `Content-Type` no soportado sigue siendo `415`.
"Sin body" significa que la request no trae ninguno — un header `Content-Type`
por sí solo no cuenta como body.
## Aceptar media types específicos [#aceptar-media-types-específicos]
Un `schema` pelado acepta únicamente `application/json`. Para aceptar otros media
types, o varios, cada uno con su propio schema, usa `content` en lugar de `schema`.
`content` reemplaza ese valor por defecto, así que lista también `application/json`
si la ruta debe seguir aceptándolo:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/webhook', {
body: {
content: {
'application/json': v.object({ event: v.string() }),
'text/plain': v.pipe(v.string(), v.minLength(1))
}
},
handler: ctx => ({ via: ctx.contentType, received: ctx.body })
})
app.listen()
```
Una request cuyo `Content-Type` no está listado responde `415` antes de parsear
nada. La comparación ignora mayúsculas y parámetros como `; charset=`, y por lo
demás es exacta: `application/vnd.api+json` no coincide con `application/json`.
El media type que coincidió es `ctx.contentType`, y `ctx.body` es la salida del
schema de ese media type — por eso su tipo es la unión de las salidas. Acotar
`ctx.body` a partir de `ctx.contentType` todavía no se verifica en tipos.
`content` solo decide qué media types acepta la ruta; no le enseña a Arcton a
leer nuevos. Un media type sin parser integrado, como `text/csv`, sigue
necesitando un
[`app.parser()`](./body-parsers.mdx#registering-your-own-parser) — sin uno
responde `415`; registrar uno nunca cambia lo que acepta un `schema` pelado.
`optional: true` funciona igual que con `schema`: una request sin
body deja `ctx.body` y `ctx.contentType` en `undefined`. Usa `schema` o
`content`, nunca ambos. [OpenAPI](../integrations/openapi.mdx) documenta cada
media type listado con su schema.
## Orden [#orden]
`body` se valida al final, después de `params` y `query` — ver
[Descripción general de validación](./overview.mdx). Un esquema de body que falla
responde con `400` de la misma forma que las fallas de params o query — ver
[Errores de validación](./validation-errors.mdx).
# Descripción general de validación (/es/docs/validation/overview)
Cualquier método HTTP también acepta un objeto de opciones en lugar de un handler
simple, lo que te permite adjuntar un esquema a `params`, `query` y/o `body`:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
query: v.object({
notify: v.optional(
v.pipe(
v.string(),
v.transform(s => s === 'true'),
v.boolean()
)
)
}),
body: v.object({
item: v.pipe(v.string(), v.minLength(1)),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
handler: ctx => ({
userId: ctx.params.id,
notify: ctx.query.notify ?? false,
order: ctx.body
})
})
app.listen()
```
`ctx.params.id` aquí es un `number`, no un `string` — la validación reemplaza
`ctx.params`, `ctx.query` y `ctx.body` con el output del esquema, así que las
coerciones y transformaciones son lo que el handler realmente ve.
## Funciona cualquier Standard Schema [#funciona-cualquier-standard-schema]
`params`, `query` y `body` aceptan cada uno cualquier
[Standard Schema](https://standardschema.dev/) — Zod 3.24+, Valibot y ArkType lo
implementan, así que cualquiera de ellos funciona aquí. Los ejemplos de esta sección
usan Valibot; mantén la consistencia con la librería de esquemas que elijas para un
proyecto.
## Orden y corte de la cadena [#orden-y-corte-de-la-cadena]
La validación corre **params → query → body**, en ese orden. El primer esquema que
falla responde de inmediato con `400` y nada más abajo en la cadena — ni el route
middleware ni el handler — corre. Ver [Errores de validación](./validation-errors.mdx)
para la forma exacta de la response.
La validación de body solo corre para una ruta que declaró un esquema de `body`, y
solo después de que el body de la request fue parseado según su `Content-Type` — ver
[Parsers de Body](./body-parsers.mdx). El middleware global corre antes que todo
esto, así que siempre ve el `ctx.params` / `ctx.query` crudo, sin transformar — ver
[Orden de ejecución](../middleware/execution-order.mdx).
Para una mirada más profunda a cada parte, ver
[Params y Query](./params-and-query.mdx) y [Body](./body.mdx).
# Params y Query (/es/docs/validation/params-and-query)
Sin un esquema, `ctx.params` viene del literal de ruta y `ctx.query` es
`Record` — ver [Context](../fundamentals/context.mdx),
[Parámetros de ruta](../routing/path-parameters.mdx) y
[Parámetros de query](../routing/query-parameters.mdx). Declarar un esquema de
`params` o `query` reemplaza el que sea con el output propio del esquema, coerciones
incluidas.
## Params [#params]
Los params de ruta siempre llegan como strings — un esquema de `params` es la forma
de convertir `:id` en algo más útil:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/users/:id', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
handler: ctx => ({ id: ctx.params.id, doubled: ctx.params.id * 2 })
})
app.listen()
```
`ctx.params.id` está tipado y valuado como `number`, así que las operaciones
aritméticas sobre él simplemente funcionan.
## Query [#query]
Los valores de query también son strings, y a menudo opcionales — un esquema de
query es donde conviertes `?limit=10` en un number real con un default real:
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.get('/search', {
query: v.object({
q: v.pipe(v.string(), v.minLength(1)),
limit: v.optional(
v.pipe(v.string(), v.transform(Number), v.number())
)
}),
handler: ctx => ({ query: ctx.query.q, limit: ctx.query.limit ?? 10 })
})
app.listen()
```
`limit` se mantiene como `number | undefined` porque es opcional — el fallback con
`??` pasa en el handler.
## Orden [#orden]
Cuando una ruta declara ambos, `params` se valida antes que `query`, y cualquiera de
los dos puede cortar la cadena con `400` antes de que corra el otro — ver
[Descripción general de validación](./overview.mdx) y
[Errores de validación](./validation-errors.mdx).
# Errores de validación (/es/docs/validation/validation-errors)
Cuando falla un esquema de `params`, `query` o `body`, Arcton responde `400` con un
body `application/json` que trae los issues que reportó el esquema:
```json
{
"issues": [
{ "message": "Invalid length: Expected >=1 but received 0", "path": ["..."] }
]
}
```
El array `issues` es exactamente lo que tu librería de esquemas devolvió en su propia
llamada de validación — Arcton no lo reestructura ni lo filtra. Todo issue tiene un
`message`, y cada librería agrega sus propios campos al lado.
Valibot, por ejemplo, devuelve issues que traen `kind`, `type`, `input`, `expected`,
`received` y `requirement`, con un `path` de objetos de segmento en lugar de keys
planas:
```json
{
"issues": [
{
"kind": "validation",
"type": "min_length",
"input": "",
"expected": ">=1",
"received": "0",
"message": "Invalid length: Expected >=1 but received 0",
"requirement": 1,
"path": [{ "type": "object", "origin": "value", "key": "item" }]
}
]
}
```
Zod y ArkType reportan sus propias formas. Lee `message` cuando necesites algo
estable entre librerías, y trata el resto como específico de la que elegiste — si un
cliente depende de los campos exactos, fija la librería de esquemas que los produce.
```ts
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({
email: v.pipe(v.string(), v.email())
}),
handler: ctx => ({ created: ctx.body })
})
app.listen()
```
Un `POST /users` con un body cuyo campo `email` falla `v.email()` recibe el `400` de
arriba; una request cuyo `email` pasa llega al handler con `ctx.body.email` ya
validado.
## Manejar tú mismo los fallos de validación [#manejar-tú-mismo-los-fallos-de-validación]
Ese `400` es el comportamiento por defecto. Un fallo de validación es un error
como cualquier otro, así que llega a
[`app.onError()`](../errors/global-error-handler.mdx#validation-errors-go-through-it-too)
como un `ValidationError` con los mismos `issues`: devuelve un valor o una
`Response` ahí para reemplazar la respuesta, o no devuelvas nada para conservar
esta.
## Qué corta la cadena y qué no [#qué-corta-la-cadena-y-qué-no]
La validación corre **params → query → body**, y el primer esquema que falla detiene
la request justo ahí — nada más en ese orden corre después, y tampoco corre ningún
route middleware ni el handler. Ver [Descripción general de validación](./overview.mdx).
Dos fallas relacionadas pasan por fuera de la validación del esquema en sí, antes de
que tu esquema llegue a ver un valor:
* Un `Content-Type` de request no soportado para una ruta con un esquema de `body`
responde `415`, antes de intentar cualquier parseo o validación.
* Un parser integrado que no puede interpretar el body en absoluto (JSON malformado,
por ejemplo) responde `400` con un
`{"issues":[{"message":"Invalid request body"}]}` fijo — este mensaje no viene de
tu esquema, porque el esquema nunca llegó a recibir un valor para validar.
Ambas están cubiertas en detalle en [Parsers de Body](./body-parsers.mdx).