Trails on Rack
See also: Guides index · Configuring Trails Applications · rack package · actionpack package · trailties package
Rack is the interface between a web server and an application: the server hands the application a request as an env object, and the application answers a status, headers and a body. A trails application is a Rack application, and much of what it does to a request happens in a stack of Rack middleware before the router sees it. This guide covers:
- How a trails app is a Rack app, and how
trails serverruns it. - Listing the middleware an app runs.
- Adding, swapping, moving and deleting middleware.
- What the default middleware do.
It assumes you know what Rack and middleware are; the rack package page introduces both.
Introduction to Rack
A Rack app is an object with a call(env) method that answers [status, headers, body]. @blazetrails/rack is the port of the Rack gem, and its types name the three parts:
import type { RackEnv, RackResponse } from "@blazetrails/rack";
export class HelloWorld {
async call(_env: RackEnv): Promise<RackResponse> {
return [200, { "content-type": "text/plain" }, ["Hello, world"]];
}
}call is async in trails, because reading a request body or a database is.
Trails on Rack
A Trails Application's Rack Object
The application is the app's Rack object. A new app's config.ts plays the part of Rails' config.ru: it boots the app, exports it, and runs the server blocks before a handler binds:
// config.ts
import { Trails } from "@blazetrails/trailties";
import "./config/environment.ts";
export const Config = Trails.application;
await Trails.application.loadServer();Trails.application.call(env) sends the request through the middleware stack and then to the router. Why the server blocks are awaited is ruled in packages/trailties/CLAUDE.md.
trails server
trails server reads config.ts and serves it through rackup's Node handler. It never starts a Vite dev server; in development bin/dev runs both, as ruled in CLAUDE.md § "importmap-rails and propshaft are out of scope".
pnpm trails server -p 3000rackup
rackup serves the same config.ts without booting through trails:
pnpm rackup config.ts -p 3000Development and Auto-reloading
The middleware stack is built once, when the app boots. Changes under app/ are reloaded on the next request by the Reloader middleware, but a change to the stack itself, or to config/, needs a server restart.
Action Dispatcher Middleware Stack
Most of the stack comes from Action Dispatch. ActionDispatch::MiddlewareStack holds it in order, and a request passes through each middleware, top to bottom, before it reaches the router.
Inspecting Middleware Stack
trails middleware prints the stack your app runs:
pnpm trails middlewareA new app prints something like this, with the app's routes at the end:
use ActionDispatch::HostAuthorization
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActionDispatch::ServerTiming
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use ActionDispatch::RemoteIp
use Trails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::ActionableExceptions
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ContentSecurityPolicy::Middleware
use ActionDispatch::PermissionsPolicy::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Rack::TempfileReaper
run Blog::Application.routesConfiguring Middleware Stack
config.middleware records changes to the default stack. They are replayed in order when the stack is built, so they may name middleware that are only added later in boot. Make them in the application class, or in an environment's file for one environment only.
Adding a Middleware
use appends a middleware to the end of the stack. insertBefore and insertAfter place it next to one already there, named by class or by index; unshift puts it first. Arguments after the class are passed to its constructor:
import { Executor } from "@blazetrails/actionpack";
import { Runtime } from "@blazetrails/rack";
import { Application } from "@blazetrails/trailties";
class Blog extends Application {
static {
this.config.middleware.use(Runtime, "X-Blog-Runtime");
this.config.middleware.insertAfter(Executor, Runtime);
}
}Swapping a Middleware
swap replaces a middleware with another in the same position:
import { ShowExceptions } from "@blazetrails/actionpack";
import { Application } from "@blazetrails/trailties";
class MyShowExceptions extends ShowExceptions {}
class Blog extends Application {
static {
this.config.middleware.swap(ShowExceptions, MyShowExceptions);
}
}Moving a Middleware
moveBefore (or move) and moveAfter take a middleware out of its place and put it next to another:
this.config.middleware.moveBefore(MyShowExceptions, ShowExceptions);
this.config.middleware.moveAfter(MyShowExceptions, ShowExceptions);Deleting a Middleware
delete removes a middleware:
import { Lock } from "@blazetrails/rack";
import { Application } from "@blazetrails/trailties";
class Blog extends Application {
static {
this.config.middleware.delete(Lock);
}
}An API-only app (config.apiOnly) starts from a smaller stack without the session, cookie and flash middleware; the API-only guide lists it.
Internal Middleware Stack
What each default middleware does, in stack order. Several are added only when a setting turns them on.
HostAuthorizationrejects a request whoseHostis not inconfig.hosts.AssumeSSLandSSLtreat requests as HTTPS behind a proxy, and force HTTPS, whenassumeSslandforceSslare set.Rack::Sendfilehands file bodies to the server through theX-Sendfileheader named byconfig.actionDispatch.xSendfileHeader.ActionDispatch::Staticserves files frompublic/whenconfig.publicFileServeris enabled.Rack::Lockserializes requests when the app is not thread-safe.ActionDispatch::Executorwraps each request in the app's executor, so per-request state is reset.ActionDispatch::ServerTimingadds aServer-Timingheader whenconfig.serverTimingis set.Rack::Runtimeadds anX-Runtimeheader with the request's time.Rack::MethodOverridereads_methodfrom a form to allowPUT,PATCHandDELETE.ActionDispatch::RequestIdgives each request anX-Request-Id.ActionDispatch::RemoteIpworks out the client's IP address.Trails::Rack::Loggerlogs the start of each request.ActionDispatch::ShowExceptionsrenders an error page for an exception, andDebugExceptionslogs it and, in development, shows the details.ActionableExceptionslets that page run a fix, such as pending migrations.ActionDispatch::Reloaderreloads changed code in development.ActionDispatch::Callbacksruns the prepare callbacks before each request.ActionDispatch::Cookies, the session store andActionDispatch::Flashset up cookies, the session and the flash.ContentSecurityPolicy::MiddlewareandPermissionsPolicy::Middlewareadd those response headers.Rack::Headempties the body of aHEADresponse.Rack::ConditionalGetandRack::ETaganswer304 Not Modifiedwhen the client's copy is fresh.Rack::TempfileReaperremoves temporary files a multipart request left behind.
Resources
Learning Rack
The rack package page covers the trails port: the env keys, Rack::Request and Rack::Response, and the middleware it ships.
Understanding Middlewares
A middleware is a Rack app that holds the next one. Its constructor takes app, and its call runs code around app.call(env):
import type { RackEnv, RackResponse } from "@blazetrails/rack";
interface RackApp {
call(env: RackEnv): Promise<RackResponse>;
}
export class Timing {
constructor(private app: RackApp) {}
async call(env: RackEnv): Promise<RackResponse> {
const started = performance.now();
const [status, headers, body] = await this.app.call(env);
console.log(`${env["PATH_INFO"]} took ${performance.now() - started}ms`);
return [status, headers, body];
}
}