Skip to content

@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.

Terminal window
pnpm add @glandjs/core @glandjs/common @glandjs/events @glandjs/http @glandjs/express reflect-metadata
@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, NodeBroker
import { AppModule } from './app.module'
const { app } = await GlandFactory.create(AppModule)
const http = app.connectTo(ExpressBroker, { poweredBy: false })
http.listen(3000)

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).

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, unmolested
http.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()

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' })
}
}

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.

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 path

Built 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 parser
http.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.

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')
})

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:

  1. onInitialize — framework settings, the error and the 404 handler
  2. the middleware queue, in call order
  3. afterMiddleware — for Fastify, whose hook chain seals once
  4. deferred plugins
  5. the routes
  6. afterRoutes — the catch-all 404, which has to sit behind the routes

Writing an adapter walks through a sixth transport from this contract.

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)
}
}

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
}

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
}
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.

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'