Actions
Actions are the server endpoints your pages call. In brust they are one Elysia 2 app, served behind the Rust server: no second port, no second router.
1Turn actions on
Install the two packages (with the rc tag; brust supports ^2.0.0-rc.0) and add an [actions] table to brust.toml. Without the table, actions are off even if actions.ts exists. Elysia 2 rc lists typebox, exact-mirror and openapi-types as peer dependencies; Bun installs them with the two packages, and if your package manager does not install peers, add them yourself.
$ bun add elysia@rc @elysia/eden@rc[actions]
# every key is optional:
# entry = "actions.ts"
# prefix = "/_brust/action"
# max_body_bytes = 1048576
# max_response_bytes = 8388608
# cross_site = "reject"
# base_url = "https://api.example.com" # actions on another origin (step 6)
# credentials = "same-origin"2Write the app
The entry default-exports an Elysia app built with the brust() adapter, and exports its type. Route methods take (path, hook, handler): the schema comes before the handler. Do not call app.listen(): Rust serves the app.
// actions.ts: a team kept in a cookie (the app the demo below mirrors in the browser)
import { brust } from '@brust/core/elysia'
import { Elysia, problem, t } from 'elysia'
const app = new Elysia({ adapter: brust() })
.get('/team', ({ request }) => ({ team: teamFromCookie(request.headers.get('cookie')), max: 6 }))
.post('/team', { body: t.Object({ id: t.Integer({ minimum: 1 }) }) }, ({ body, request, set }) => {
const team = teamFromCookie(request.headers.get('cookie'))
if (team.length >= 6) return problem(409, { title: 'TeamFull', detail: 'the team already has 6 members', max: 6 })
return save(set, [...team, member(body.id)])
})
.delete('/team/:id', { params: t.Object({ id: t.Integer({ minimum: 1 }) }) }, ({ params, request, set }) =>
save(set, teamFromCookie(request.headers.get('cookie')).filter((m) => m.id !== params.id)))
export default app
export type App = typeof appEvery request under the prefix, /_brust/action by default, goes to this app in a Bun worker. Rust answers CORS preflights, caps the request body (413) and the response size, before and after your code.
3Call it from a component
client<App>() from @brust/core/client is a typed Eden Treaty client, already pointed at the prefix. Import the app's type only: a value import would pull Elysia into the browser, and the build refuses it.
// components/team-client.ts
import { client } from '@brust/core/client'
import type { App } from '../actions' // a type import: no Elysia in the browser
import { team } from './team-store'
const api = client<App>()
export async function addMember(id: number): Promise<string> {
const r = await api.team.post({ id })
if (r.error) return r.error.status === 409 ? 'team full' : `failed with status ${r.error.status}`
team.members.set(r.data.team)
return ''
}Every call resolves to { data, error, status, response, headers }, with exactly one of data and error set. A network failure resolves with status 503.
Middleware
client({ middleware }) takes a list of functions between the typed client and fetch. Each gets the request Eden built and a next that sends it on; middleware[0] is the outermost. A link can add a header, answer without calling next, or call next again: after a 401 it renews the session and sends the same request once more. Every next(r) sends its own copy of r, so a retry carries the same JSON or multipart body. A link that throws is a network failure (status 503). The client keeps its route types.
// api.ts
import { type ActionMiddleware, client } from '@brust/core/client'
import type { App } from './actions'
let generation = 0 // counts renewals; a call that failed before the last one just retries
let renewing: Promise<boolean> | undefined
const renewSession = (seen: number) =>
seen !== generation
? Promise.resolve(true)
: (renewing ??= fetch('/_brust/action/session/refresh', { method: 'POST' })
.then((r) => {
if (r.ok) generation++
return r.ok
})
.finally(() => { renewing = undefined }))
const renew: ActionMiddleware = async (req, next) => {
const seen = generation
const res = await next(req)
if (res.status !== 401) return res
return (await renewSession(seen)) ? next(req) : res // the SAME req, sent again
}
const org: ActionMiddleware = (req, next) => {
const r = new Request(req) // a copy to change; `req` stays unread
r.headers.set('x-org', currentOrg())
return next(r)
}
export const api = client<App>({ middleware: [renew, org] })brust has no built-in token renewal, because auth schemes differ; the single-flight above renews once for every call that fails together. The renewal itself uses plain fetch, so it does not pass through the chain.
Typed routes
- Routes registered on an
anyapp, or in a function that does not return the chained instance, give the client no types. Writeexport const auth = new Elysia().post(…)andapp.use(auth). - A handler that returns a
Responsegivesdataan untyped body. Return a value, orstatus(code, body)/problem(), and the client narrowserror.statusanderror.value. - An action may set several cookies and return a typed
status(401, …): everySet-Cookieheader reaches the client.
The whole path in one example: a chained plugin with t schemas for the body and each response, a cookie set on the answer, a typed 401, app.use(plugin), and a client with middleware that still narrows data and error.value. The schemas are Elysia's (see Validation in docs/actions.md); the status answers are covered in Errors and limits.
// actions/auth.ts
import { Elysia, status, t } from 'elysia'
export const auth = new Elysia().post(
'/login',
{
body: t.Object({ user: t.String(), pass: t.String() }),
cookie: t.Cookie({ sid: t.Optional(t.String()), csrf: t.Optional(t.String()) }),
response: {
200: t.Object({ user: t.String() }),
401: t.Object({ error: t.Literal('bad credentials') }),
},
},
async ({ body, cookie }) => {
if (!(await checkLogin(body.user, body.pass))) return status(401, { error: 'bad credentials' })
cookie.sid.set({ value: newSession(body.user), httpOnly: true, path: '/' })
cookie.csrf.set({ value: newCsrf(), path: '/' })
return { user: body.user }
},
)
// actions/index.ts
import { brust } from '@brust/core/elysia'
import { Elysia } from 'elysia'
import { auth } from './auth'
const app = new Elysia({ adapter: brust() }).use(auth)
export type App = typeof app
// api.ts: `renew` is the middleware from the recipe above
import { client } from '@brust/core/client'
import type { App } from './actions'
const api = client<App>({ middleware: [renew] })
export async function login(user: string, pass: string) {
const r = await api.login.post({ user, pass }) // a wrong body is a type error
if (r.error?.status === 401) return r.error.value.error // 'bad credentials'
return r.data?.user // string | undefined
}4Try it
On this site the demo runs in your browser; with [actions] on a brust server the same buttons call POST /_brust/action/team. The rules are the app's above: at most 6, a Pokémon already in the team is not added twice, and the seventh gets the TeamFull 409. The team is kept in your browser's storage and goes into the team store that the buttons read. The Store page shows the same team.
Team 0 / 6. Add a seventh to see the 409.
5Errors and limits
return problem(409, { title: 'TeamFull', max: 6 }) // returned: typed on the client
throw new TeamFull(6) // an HTTPError.id('TEAM_FULL') subclass: unknown on the client
throw new Error('boom') // 500 problem+json, detail only outside production- An unknown path or a wrong method under the prefix is a 404 problem+json from Elysia; there is no 405.
- Outside the prefix, a non-GET request to a page is a 405 from Rust.
- A page or loader route may sit under the prefix: a
GETorHEADit matches is the route's, and everything else there stays the app's (any other method, aGETno route under the prefix matches; the*catch-all never counts). A generic route outside the prefix, such as/{a}/{b}, never takes a path under the prefix; only a route whose own pattern is under it does. So an OAuthGETcallback at/auth/{provider}/callbackcan be a loader that sets a cookie and redirects while Apple'sform_postto the same path stays an action. AGETaction shadowed this way is named in a boot warning. The build refuses a route equal to the prefix and a{*rest}route under it. - Cross-site requests are rejected by default (
cross_site = "reject"). Behind a proxy, passHostthrough or setX-Forwarded-Host, or same-origin requests other thanGETget a 403.
A store written inside an action is per-request and never reaches the page. Return the data and set the store in the browser with the reply, as addMember does.
Streaming uploads
A request body is read whole before your code runs, up to max_body_bytes (1 MiB by default, 64 MiB at most). To take a larger upload, such as an archive, declare the route with { parse: 'none' } and list it in brust.toml: stream = ["POST /upload"] (paths are relative to the prefix; POST, PUT or PATCH). Your handler then reads request.body as a stream, and the server reads the socket only as fast as you read it, so memory stays at about 2 MiB per upload whatever its size, up to max_stream_bytes (256 MiB by default, 4 GiB at most). A { parse: 'none' } route that is not listed stays buffered and capped, with a boot warning.
- A
Content-Lengthovermax_stream_bytes, or a body that passes it, is a 413; the body is counted as it arrives. - A client that sends nothing for
stream_idle_ms(30 s) or an upload that runs paststream_total_ms(15 min) is a 408. A body shorter than itsContent-Lengthis a 400; your read rejects, never a short success. - More than
max_streamsuploads at once (a quarter of the worker slots by default) is a 503 withRetry-After: 1, before a byte is read. An upload holds one worker slot while it runs. - The status is the server's, whatever your app answered. An app may answer early (an auth check before the upload); the server then reads and discards the rest for up to 2 seconds, so a client still sending reads the answer.
- On Cloudflare Workers the platform's own stream is passed through and counted against
max_stream_bytes; the idle and total timeouts andmax_streamsare ignored. Cloudflare's request-body limit applies first: 100 MB on Free and Pro, 200 MB on Business, up to 5 GB on Enterprise (see Workers limits). A body that fails on its way in fails the call with 400 even if your app caught the error. An app that answers with the request body itself (new Response(request.body)) hands the stream on after the ceiling check, so past the ceiling the response errors mid-flight instead of answering 413: read the body before you answer if you need the 413. - Under
brust devan upload of any allowed size passes through the dev server as it arrives.
Compression
A reply of 1 KiB or more with a text, JSON, JavaScript, XML or SVG content type is gzip-compressed for a client that accepts gzip, as pages are. Such a reply carries Vary: Accept-Encoding whether or not the client accepts gzip. A strong ETag is dropped from a compressed reply because the bytes change; a weak one stays. A reply that already has a Content-Encoding is left as it is. Compression can leak a secret when one reply holds both a secret token (a CSRF token, say) and input the request reflected back: an attacker who controls the reflected part can learn the token from the compressed size. The cross-site guard refuses a cross-site request other than GET, HEAD or OPTIONS from an origin not listed in [cors], so the replies most exposed are those of GET actions (which pass the guard) and of actions on a server with cross_site = "allow". Set Cache-Control: no-transform on such a reply to opt out.
6Actions on their own origin
The pages and the actions can be two deployments: static pages on Cloudflare Pages and the actions on api.example.com, or an API server next to a front end hosted elsewhere. One build flag on the actions side, one setting on the pages side.
The actions deployment
brust build --actions-only builds a dist/ with no pages: no routes, no templates, no jobs, no client chunks. The app still runs behind the same Rust admission: method gate, body caps, Content-Encoding, the cross-site guard and CORS. Every path outside the prefix is a 404 application/problem+json.
[actions]
entry = "actions.ts"
prefix = "/" # only in an --actions-only build
[cors]
origins = ["https://app.example.com"] # the exact page origin
credentials = true # only if the page sends cookies$ brust build --actions-only
$ brust start- It combines with
--target bun(the default:brust startserves it) and--target cloudflare(a Worker with only actions and no Static Assets). It cannot be combined with--target static, and it needs an[actions]table.[cache]and route options are ignored, with an info line. prefix = "/"is allowed only here (and in a page-only build that points at such a deployment), sohttps://api.example.com/teamis the app's/team. A normal build refuses it: its page routes would be unreachable.- Any other prefix starts with
/, has no trailing/, uses only[A-Za-z0-9._~-]segments (never.or..), and stays out of/_brust/; the default/_brust/actionis the one exception. - Your routes are still written without the prefix and
request.urlis the real URL. The server's own paths (/ping,/_brust/...,/public/...) stay the server's.
The pages deployment
On the pages side, [actions] base_url tells the browser client where the actions live, and credentials sets the default RequestInit.credentials of every call.
[actions]
base_url = "https://api.example.com" # an origin: no path, query, fragment or credentials
prefix = "/" # the prefix the other deployment mounts at
credentials = "include" # same-origin (default) | include | omit- Both are runtime settings, like
[cors]: each environment points at its own API without a rebuild.base_urlcomes from the envBRUST_ACTIONS_BASE_URL, thenrun({ config: { actionsBaseUrl } }), then the toml.credentialscomes fromrun({ config: { actionsCredentials } }), then the toml. - The server injects them into every page, next to the prefix, as JSON string literals that are safe inside a script:
<script>globalThis.__BRUST_ACTION_PREFIX__="/"</script><script>globalThis.__BRUST_ACTION_BASE__="https://api.example.com";globalThis.__BRUST_ACTION_CREDENTIALS__="include"</script>- The client resolves the base as
client({ baseUrl }), then the page's injected base, then the page's own origin. The typed client keeps importingtype Appfrom the shared source, so calls stay typed across the two deployments. initpassed toclient()overrides the credentials default for that client.- A page-only build. With a
base_urland noactions.ts, the build bundles no actions and mounts no local app; the base and prefix are still injected. A missing file thatentrynames explicitly is an error, never a page-only build. - With
--target static, the base is baked into the rendered pages from the build's environment. That is how static pages on Pages call actions on their own domain. See Deployment.
7Calling across origins
Three things decide whether a cross-origin call works: the actions server's [cors], its cross-site guard, and the browser's rule for credentials. Change the settings below to see each step.
browser cross-origin: the browser first sends OPTIONS https://api.example.com/… (Eden's JSON content-type makes it a preflighted request)
server 204 preflight from Rust, Access-Control-Allow-Origin: https://app.example.com, Access-Control-Allow-Credentials: true
server POST: the cross-site guard lets it through, the Origin is listed by name
server your Elysia app answers; Rust stamps the CORS headers on the response
browser cookies travel both ways, if the action set them with SameSite=None; Secure
=> reaches your app- Every cross-origin call is preflighted, GET included: the client sends JSON. Rust answers the preflight of a listed origin with a 204 and the CORS headers. Any other origin gets no CORS headers, and the browser never sends the call.
- A cross-site request other than
GET,HEADorOPTIONS(aPOST, say) from an origin not listed by name in[cors] originsis a403 CrossSiteRejected, before the body is read. A wildcard"*"does not count;cross_site = "allow"turns the guard off. credentials = "include"needs the exact page origin in[cors] originsandcredentials = true.credentials = truewith"*"is a boot error.- A cookie that must travel cross-site needs
SameSite=None; Secure. Browsers treathttp://localhostandhttp://127.0.0.1as secure, so this works in development.
.post('/login', ({ cookie: { session } }) => {
session.set({ value: token, httpOnly: true, sameSite: 'none', secure: true, path: '/' })
return { ok: true }
})