@glandjs/http@1.1.0-beta
@glandjs/http
The framework-agnostic HTTP core — route decorators, HttpContext, the middleware onion, HttpCore, HttpBroker and the adapter contract.
@glandjs/http is everything HTTP that is not a particular server. It owns the
route decorators, the abstract context, the promise-based middleware onion, the
request lifecycle, CORS, cookies, problem details and the lifecycle events. It does
not import a server, a router or a framework.
One core, five transports. The same controller, the same middleware and the same
assertions produce the same results on Express, Fastify, Koa, Hono and node:http.
pnpm add @glandjs/core @glandjs/common @glandjs/events @glandjs/http @glandjs/express reflect-metadataThe two layers
Section titled “The two layers”@glandjs/http |
An adapter | |
|---|---|---|
| Owns | reply coercion, the middleware onion, the request lifecycle, CORS, cookies, problem details, path normalisation, SSE framing | building a context, putting a route on a router, mounting one framework middleware, writing a reply, binding and releasing the socket |
| Knows about Express | nothing | everything |
// The adapter changes. Nothing else does.import { GlandFactory } from '@glandjs/core'import { ExpressBroker } from '@glandjs/express' // or FastifyBroker, KoaBroker, HonoBroker, NodeBrokerimport { AppModule } from './app.module'
const { app } = await GlandFactory.create(AppModule)const http = app.connectTo(ExpressBroker, { poweredBy: false })
http.listen(3000)Route decorators
Section titled “Route decorators”Twenty-one verb decorators plus @RequestMapping. Every one takes the same optional
argument and writes the same two metadata keys.
import { Get, Post, Put, Patch, Delete, Head, Options, All, Trace, Connect, Purge, Search, Propfind, Proppatch, Mkcol, Copy, Move, Lock, Unlock, Acl, Report, RequestMapping, RequestMethod,} from '@glandjs/http'Each one is (path?: string | string[]) => MethodDecorator & PropertyDecorator. The
default path is '/', and an empty path is normalised to '/'.
@Controller('/products')export class ProductController { @Get() list(ctx) {} @Get('/:id') find(ctx) {} @Post() create(ctx) {}
// Any of the 33 RequestMethod members, including the extended ones. @RequestMapping({ path: 'search', method: RequestMethod.SEARCH }) search(ctx) {}}RequestMethod is the full set: the seven everyday verbs plus ALL, CONNECT,
TRACE, PURGE, SEARCH, the WebDAV verbs (COPY, LOCK, MKCOL, MOVE,
PROPFIND, PROPPATCH, UNLOCK), ACL, the binding verbs (BIND, REBIND,
UNBIND), the versioning verbs (CHECKOUT, MERGE, MKACTIVITY, MKWORKSPACE,
REPORT, UPDATE) and the SSE verbs (NOTIFY, SUBSCRIBE, UNSUBSCRIBE).
HttpCore
Section titled “HttpCore”The application object connectTo() hands back. Almost every method is fluent.
class HttpCore { constructor(adapter: HttpServerAdapter, options?: HttpApplicationOptions)
// identity get broker(): HttpEventBroker get id(): string get instance(): TApp // the raw framework app get settings(): HttpApplicationSettings get routes(): readonly RegisteredRoute[] get middleware(): readonly MiddlewareEntry[] get port(): number | undefined
// lifecycle listen(port: number, options?: ServerListening): this ready(): Promise<this> close(): Promise<void>
// middleware use(middleware): this use(path: string | string[], middleware): this useRaw(...args): this setErrorHandler(handler): this enableCors(config?): this
// routing — 20 verb shortcuts, plus: registerRoute(method, path, action, origin?): this
// configuration setGlobalPrefix(prefix): this useStaticAssets(path, options?): this setViewEngine(engine): this setBaseViewsDir(directory): this bodyParser(options | false): this json(options?): this urlencoded(options?): this text(options?): this multipart(options?): this raw(options?): this
// observability on(event, listener): this off(event, listener): this handleError(error, message): void}const http = app.connectTo(ExpressBroker)
http.use(async (ctx, next) => { const started = Date.now() await next() console.log(`${ctx.method} ${ctx.path} ${Date.now() - started}ms`)})http.useRaw(compression()) // framework middleware, unmolestedhttp.enableCors({ origin: 'https://example.com', credentials: true })http.useStaticAssets('public', { prefix: '/static' })http.bodyParser({ json: true, urlencoded: { extended: true }, limit: '1mb' })
http.listen(3000, { host: '0.0.0.0' })await http.ready()HttpContext
Section titled “HttpContext”The abstract context. Every adapter provides a concrete subclass, so a controller receives the same shape on every transport.
abstract class HttpContext<TRequest, TResponse, TEvents> extends Context<TEvents> { // state params: Record<string, string> requestId: string startedAt: number aborted: boolean written: boolean req: TRequest res: TResponse
// request get body(): any get method(): RequestMethod get path(): string get url(): string get originalUrl(): string get query(): Record<string, string | string[] | undefined> get headers(): Record<string, string | string[] | undefined> get hostname(): string get ip(): string | undefined get protocol(): string get secure(): boolean get xhr(): boolean get stale(): boolean get fresh(): boolean get subdomains(): string[] get host(): string | undefined is(type): string | false | null accepts(types?): string | false
// response — all fluent status(code): this redirect(url, status?): this send(data, statusCode?, headers?): this json(data, statusCode?, headers?): this html(body, statusCode?, headers?): this text(body, statusCode?, headers?): this xml(body, statusCode?, headers?): this end(): this sendFile(path, options?, callback?): this download(path, filename?, options?): this attachment(filename?): this location(url): this vary(fields): this get responded(): boolean
// headers — the request/response split is explicit getHeader(name): HttpHeaderValue // request getResponseHeader(name): HttpHeaderValue // response setHeader(name, value): this setHeaders(headers): this hasHeader(name): boolean hasResponseHeader(name): boolean removeHeader(name): this
// cookies get cookies(): RequestCookies get signedCookies(): RequestCookies getCookie(name): string | undefined setCookie(name, value, options?): this clearCookie(name, options?): this deleteCookie(name, options?): this
// gland + errors throw(status, options?): this sse(options?): SseStream get elapsed(): number get lifecycle(): HttpEventBroker}Inherited from Context: state, setState(), error, emit(), call(), on(),
once(), off().
@Controller('/products')export class ProductController { @Get('/:id') async find(ctx: HttpContext) { // ctx.call() reaches a channel by name — no import, no injection return { product: await ctx.call('db:product:find', { id: ctx.params.id }) } }
@Get('/search') search(ctx: HttpContext) { // a repeated query key becomes an array return { tags: ctx.query.tag } }
@Get('/gone') gone(ctx: HttpContext) { // throws nothing: it writes an RFC 7807 document and marks the context written return ctx.throw(HttpStatus.GONE, { detail: 'removed' }) }}A handler returns a value, not a response
Section titled “A handler returns a value, not a response”The return value is the response. respond() is skipped when the context already
answered, so returning ctx.send(...) and returning a plain object are both correct.
| You return | The client gets |
|---|---|
undefined |
nothing |
| a plain object or array | application/json |
| a number or boolean | application/json |
| a string | text, or HTML when it looks like HTML |
a Buffer / Uint8Array |
bytes |
a Readable |
piped |
an SseStream |
text/event-stream |
an HttpReply |
exactly what it says |
import { HttpReply } from '@glandjs/http'
@Get('/created')created(ctx) { return HttpReply.json({ id: 'p1' }, { status: 201, headers: { location: '/products/p1' } })}HttpReply has nine constructors: json, text, html, xml, buffer, stream,
file, redirect and empty.
Middleware
Section titled “Middleware”A promise onion, in the Koa model rather than the Express one: await next() really
waits, and a downstream throw reaches an upstream catch.
http.use(async (ctx, next) => { const started = Date.now() await next() console.log(`${ctx.method} ${ctx.path} ${Date.now() - started}ms`)})
http.use('/admin', adminGuard) // scoped to a pathBuilt in, with no extra dependency:
import { createCorsMiddleware, bodyLimitMiddleware, withErrors } from '@glandjs/http'
http.use(createCorsMiddleware({ origin: 'https://example.com', credentials: true }))http.use(bodyLimitMiddleware(1_000_000)) // before any body parserhttp.setErrorHandler(myRenderer)The default renderer produces RFC 7807 problem details and drops the message for
anything that is not an HttpException — the message is still logged on
http:request:error.
The lifecycle events
Section titled “The lifecycle events”One bus carries eight events. It is observability, not control flow.
| Event | Fires |
|---|---|
http:route:registered |
a route is added to the table |
http:route:miss |
no route matched |
http:request:start |
{ id, method, path, url, ip } |
http:request:end |
{ status, duration } — always |
http:request:error |
only when the handler threw |
http:server:listening |
the socket is bound, with the resolved port |
http:server:closed |
shutdown finished |
http:server:crashed |
a startup or runtime failure — the one to watch |
import { HttpEvent } from '@glandjs/http'
http.on(HttpEvent.ServerCrashed, ({ message, error }) => { logger.error({ message, error }, 'http server')})HttpServerAdapter
Section titled “HttpServerAdapter”The whole extension seam. An adapter implements eleven members; everything else is inherited from the base class, which is what keeps the five transports agreeing.
abstract class HttpServerAdapter<TServer, TApp, TRequest, TResponse, TContext> { constructor(instance: TApp, options?: HttpApplicationOptions)
// what an adapter implements abstract onInitialize(options?): void | Promise<void> abstract createContext(req, res, events?): TContext // idempotent per request abstract registerRoute(method, path, action, origin?): void abstract useOne(...args): unknown abstract bridgeGland(entry, request?, response?, next?): (...args) => unknown abstract write(ctx, payload: ReplyPayload): void | Promise<void> abstract responded(ctx): boolean // never double-write abstract bodyParser(options | false): void abstract useStaticAssets(path, options?): void abstract listen(port, options?): void | Promise<void> abstract close(): Promise<void>
// what it may override protected afterMiddleware(): void | Promise<void> protected afterRoutes(): void | Promise<void> protected beforeFlush(): void protected syncParams(ctx, req): void
// what it inherits initialize(options?): Promise<void> finalize(): Promise<void> route(method, path, action, origin?): RegisteredRoute dispatch(route, req, res): Promise<TContext> respond(result, ctx): Promise<void> notFound(ctx): Promise<void> crash(message, error): void use(...): this useRaw(...): this defer(work): this setGlobalPrefix(prefix): this routeTable: readonly RegisteredRoute[]}Two rules make the contract work: createContext is memoised per request, and write
is only ever called once per response.
Ordering is decided once, by buffering. finalize() always runs the same six steps:
onInitialize— framework settings, the error and the 404 handler- the middleware queue, in call order
afterMiddleware— for Fastify, whose hook chain seals once- deferred plugins
- the routes
afterRoutes— the catch-all 404, which has to sit behind the routes
Writing an adapter walks through a sixth transport from this contract.
HttpBroker
Section titled “HttpBroker”The bridge that turns gland:define:route into real routes.
class HttpBroker<TEvents, TApp, TOptions> extends BrokerAdapter<TEvents, TApp, TOptions> { constructor(instance: TApp, options?: TOptions) initialize(): TApp get routeCount(): number}initialize() subscribes to gland:define:route, registers every route it receives
with its fullPath, and — when none arrive — logs a loud, specific error rather than
leaving you with a silent zero-route table.
export class ExpressBroker<TEvents> extends HttpBroker<TEvents, ExpressCore<TEvents>> { constructor(options?: HttpApplicationOptions) { super(new ExpressCore<TEvents>(options), options) }}HttpEventBroker
Section titled “HttpEventBroker”An EventBroker with three additions, used for the lifecycle bus.
class HttpEventBroker<TEvents> extends EventBroker<TEvents> { safeEmit(event, payload): boolean // false when nobody was listening hasListener(event): boolean observe(event, listener): () => void // returns an unsubscribe function}SseStream
Section titled “SseStream”Server-sent events are implemented, not a placeholder.
@Get('/events')stream(ctx) { const sse = ctx.sse({ heartbeat: 15_000, retry: 3_000 }) sse.event('tick', { at: Date.now() }) sse.comment('keep-alive') return sse}Options
Section titled “Options”interface HttpApplicationOptions { prefix?: string bodyParser?: BodyParserOptions | false // default false poweredBy?: string | false // default 'Gland' logLevel?: 'info' | 'error' | 'warn' | 'debug' | 'verbose' trustProxy?: boolean | number | string https?: HttpsOptions views?: { engine: unknown; directory: string | string[]; extension?: string } static?: readonly { root: string; prefix?: string; options?: Record<string, unknown> }[]}
interface BodyParserOptions { json?: boolean | JsonBodyParserOptions urlencoded?: boolean | UrlencodedBodyParserOptions multipart?: boolean | MultipartBodyParserOptions text?: boolean | TextBodyParserOptions raw?: boolean | RawBodyParserOptions limit?: number | string // default 102400 — 100 kB, not the framework's own default inflate?: boolean}Implemented in this package, for all five adapters, with no dependency on the cors
package. Defaults match that package deliberately.
| Option | Default |
|---|---|
origin |
'*' |
methods |
GET, HEAD, PUT, PATCH, POST, DELETE |
credentials |
false |
maxAge |
600 |
vary |
true |
optionsSuccessStatus |
204 |
http.enableCors({ origin: 'https://example.com', credentials: true, maxAge: 86_400 })maxAge is clamped to 600 because Chrome and Firefox both cap preflight caching at
ten minutes. credentials: true together with origin: '*' is a contradiction and is
rejected at boot rather than at request time.
Cookies
Section titled “Cookies”interface CookieOptions { maxAge?: number // MILLISECONDS path?: string // default '/' domain?: string sameSite?: 'strict' | 'lax' | 'none' | boolean secure?: boolean httpOnly?: boolean signed?: boolean secret?: string | string[] expires?: Date}maxAge is milliseconds in Gland. @fastify/cookie uses seconds; the adapter
converts, so the value you write is the value you mean.
HttpStatus and HttpException come from @medishn/toolkit, and Context from
@glandjs/core. Neither is re-exported here.
import { HttpStatus, HttpException, type Logger } from '@medishn/toolkit'import type { Context } from '@glandjs/core'See also
Section titled “See also”- HTTP layer overview — the generated map of the mirrored docs
- Choosing an adapter
- Adapter matrix
- Changelog — including the pending changesets