@fluojs/platform-express
v1.1.0
Published
Express-based HTTP adapter for the Fluo runtime.
Downloads
123
Maintainers
Readme
@fluojs/platform-express
Express-backed HTTP adapter for the fluo runtime.
Table of Contents
- Installation
- When to Use
- Quick Start
- Common Patterns
- Adapter Contract
- Public API Overview
- Related Packages
- Example Sources
Installation
npm install @fluojs/platform-express express@fluojs/platform-express requires Node.js 20 or newer. Its package manifest declares engines.node >=20.0.0; choose a fetch-style adapter instead when the deployment host is Bun, Deno, or Cloudflare Workers.
When to Use
Use this package when you want to run a fluo application using Express as the underlying HTTP engine. This is useful when existing Express operational assets, hosting conventions, or server integrations need to stay near the platform boundary while controllers, providers, guards, interceptors, and middleware keep using fluo's runtime contracts.
Keeping Express as the host does not preserve NestJS legacy decorator or reflection-metadata semantics. Before changing the HTTP host, migrate controllers and providers to TC39 standard decorators, declare constructor tokens with class-level @Inject(...), and use explicit module/provider registration. Keep experimentalDecorators and emitDecoratorMetadata disabled; an Express adapter replacement is not a compatibility layer for NestJS dependency discovery.
Express compatibility does not mean that native Express/Connect (req, res, next) middleware can be passed directly to fluo's application-level middleware option. That option accepts fluo middleware (handle(context, next)) or route-scoped fluo middleware providers. Register migration-only native handlers through the adapter's explicit nativeMiddleware option, or wrap the behavior behind the fluo Middleware contract so it remains portable to Fastify, raw Node.js, Bun, Deno, and Workers adapters.
Quick Start
import { createExpressAdapter } from '@fluojs/platform-express';
import { fluoFactory } from '@fluojs/runtime';
import { AppModule } from './app.module';
const app = await fluoFactory.create(AppModule, {
adapter: createExpressAdapter({ port: 3000 }),
});
await app.listen();createExpressAdapter() defaults to port 3000 and does not read process.env.PORT; invalid explicit numeric options such as port, maxBodySize, retryDelayMs, retryLimit, and shutdownTimeoutMs throw during adapter setup. maxBodySize and shutdownTimeoutMs are non-negative integer byte/time limits, so 0 is valid: maxBodySize: 0 allows only empty request bodies, and shutdownTimeoutMs: 0 force-closes connections as soon as shutdown yields to the timer queue.
Common Patterns
Handling Streaming Responses (SSE)
The Express adapter supports Server-Sent Events (SSE) via the shared SseResponse utility, abstracting away the Express-specific stream handling.
Express-backed response streams also honor the shared fluo backpressure contract: response.stream.waitForDrain() settles on drain, close, or error, so streaming writers do not hang when clients disconnect before backpressure clears.
import { Sse, SseResponse, type RequestContext } from '@fluojs/http';
@Sse('events')
async streamEvents(_input: undefined, ctx: RequestContext) {
const events = new SseResponse(ctx);
events.send({ data: 'hello' }, { event: 'ready' });
return events;
}Body Parsing and Multipart
rawBody preservation is opt-in (rawBody: true), and multipart requests do not expose rawBody. When you construct the adapter directly, pass multipart limits as the second argument. bootstrapExpressApplication(...) and runExpressApplication(...) accept the same multipart settings under options.multipart. When multipart.maxTotalSize is not set, maxBodySize becomes the default total multipart payload cap so body-size limits stay portable across HTTP adapters.
const adapter = createExpressAdapter(
{
port: 3000,
rawBody: true,
},
{
maxTotalSize: 10 * 1024 * 1024,
},
);Express/Connect Middleware Boundary
The Express adapter preserves Express as the host HTTP engine, but request pipeline middleware remains dispatcher-owned. Register portable middleware through the fluo Middleware contract:
import type { Middleware } from '@fluojs/http';
const compressionHeaders: Middleware = {
async handle(context, next) {
context.response.setHeader('vary', 'Accept-Encoding');
await next();
},
};
const app = await fluoFactory.create(AppModule, {
adapter: createExpressAdapter({ port: 3000 }),
middleware: [compressionHeaders],
});Do not pass an Express/Connect function such as compression() directly as fluo middleware. If a migration must retain a native handler, register it explicitly before adapter construction completes:
import type { RequestHandler } from 'express';
const legacyRequestTag: RequestHandler = (_request, response, next) => {
response.setHeader('x-migration-host', 'express');
next();
};
const adapter = createExpressAdapter({
nativeMiddleware: [legacyRequestTag],
port: 3000,
});nativeMiddleware is mounted in array order before the adapter's Express Router and catch-all fluo dispatch. Calling next() continues into fluo middleware, guards, interceptors, and handlers. Ending the native response stops there without entering fluo dispatch. Thrown/rejected errors and next(error) remain in the Express error chain, so place any native Express error handler after the middleware it handles in the same array; fluo error filters and envelopes do not translate failures that occur before dispatch.
The native stack is fixed when the adapter is created. The adapter owns its Node HTTP/S listener and connections, but it does not discover or dispose timers, clients, or other resources captured by native middleware; application bootstrap code must release those resources. Keep route behavior, request-context mutation, and cross-platform concerns in fluo middleware, guards, or interceptors.
Native Route Registration with Safe Fallback
The adapter pre-registers semantically safe Express Router handlers for explicit GET, POST, PUT, PATCH, DELETE, and HEAD routes and still dispatches those requests through the shared fluo dispatcher.
For semantically safe unversioned routes, Express hands the pre-matched descriptor and params to the shared dispatcher so eligible singleton-safe handlers can complete on the dispatcher fast path and other handlers can fall back without duplicate route matching, while guards, interceptors, observers, body parsing, raw body capture, SSE, and error responses stay on the same framework-owned execution path.
If app middleware rewrites the framework request method or path after the adapter attaches a native handoff, the dispatcher treats that handoff as stale and rematches the rewritten request instead of reusing the original Express match.
To avoid changing documented fluo semantics, overlapping same-shape param routes such as /:id and /:slug, @All(...) handlers, OPTIONS ownership, non-URI versioning, and requests that rely on fluo's duplicate-slash/trailing-slash normalization stay on the catch-all fallback path.
Startup Retry and Shutdown
listen() retries EADDRINUSE according to retryDelayMs and retryLimit only while the adapter remains open. Concurrent listen() calls share the first caller's in-flight startup lifecycle and dispatcher instead of starting overlapping retry loops. If close() is called while startup is waiting in that retry loop, the adapter aborts the shared listen attempt and waits for it to settle before close() resolves, even when the underlying Node server has not reached the listening state yet. A listen() call made while close() is in progress rejects and can be retried after close() resolves. Releasing the blocked port after close() resolves cannot make the adapter bind later; callers must invoke listen() again explicitly to start it.
Adapter Contract
- Shared dispatcher ownership: Native Express Router matches still hand off to the shared fluo dispatcher, so middleware, guards, interceptors, observers, params, and error envelopes remain framework-defined.
- Host engine boundary: Express is the host/platform HTTP engine, but fluo does not reinterpret native Express/Connect middleware as fluo middleware; application-level middleware must implement the shared
Middlewarecontract, while the platform-specificnativeMiddlewareoption mounts native handlers before routing. - Native middleware ownership: Native handlers run in declared order and retain Express continuation, response termination, and error-chain semantics. Adapter shutdown closes the listener and connections but does not dispose resources owned by those handlers.
- Safe fallback scope:
@All(...)handlers and overlapping same-shape param routes intentionally stay on the catch-all fallback path instead of being force-registered through Express Router. - OPTIONS ownership parity: The adapter prevents Express Router from auto-answering
OPTIONSfor native routes, so unsupported methods still fall through to fluo dispatcher semantics and@All(...)handlers can continue to ownOPTIONSwhen defined. - Path normalization parity: Requests that Express Router does not normalize the same way as fluo, such as duplicate-slash variants, still resolve through fallback dispatch so fluo's normalized route contract is preserved.
- Versioning parity: Header/media-type/custom version selection remains dispatcher-owned even when Express Router handles the initial path match.
- Middleware rewrite parity: App middleware that rewrites method or path invalidates native handoff and rematches the rewritten request.
- Response serialization parity: String responses default to
text/plain, objects/arrays serialize as JSON, binary payloads default toapplication/octet-stream, andset-cookievalues are merged. - Startup and shutdown: The adapter supports HTTP/HTTPS startup, retries
EADDRINUSEaccording to retry options untilretryLimitis exhausted while the adapter is open, reuses one in-flight listen lifecycle and its dispatcher for concurrent startup callers, aborts and joins that shared retry loop duringclose()before shutdown completion is reported, rejectslisten()while close is in progress, treats duplicatelisten()calls on an already-started adapter as idempotent without replacing the live dispatcher, drains idle keep-alive sockets on normal close, reuses one in-flight close lifecycle for concurrentclose()calls, and can force-close connections after shutdown timeout, including immediate force-close whenshutdownTimeoutMsis0.
Public API Overview
createExpressAdapter(options): Factory for the Express HTTP adapter.bootstrapExpressApplication(module, options): Advanced bootstrap helper for manual control.runExpressApplication(module, options): Compatibility helper for quick startup with signal wiring. On timeout/failure it reports the condition through logging andprocess.exitCode, while leaving final process termination to the surrounding host.isExpressMultipartTooLargeError(error): Normalizes multipart limit detection across adapter error shapes.ExpressHttpApplicationAdapter: The core adapter implementation class.getServer()exposes the underlying Node HTTP/HTTPS server for narrow platform integrations,getListenTarget()reports the resolved bind target and public URL after startup, andgetRealtimeCapability()returns the server-backed capability used by realtime packages. Keep these helpers at infrastructure boundaries instead of threading native server objects through ordinary application code.- Option types:
ExpressAdapterOptions,BootstrapExpressApplicationOptions,RunExpressApplicationOptions,ExpressNativeMiddleware,CorsInput,ExpressApplicationSignal.
createExpressAdapter(options, multipartOptions?) supports host, https, maxBodySize, nativeMiddleware, port, rawBody, retryDelayMs, retryLimit, and shutdownTimeoutMs. Direct ExpressHttpApplicationAdapter construction applies the same numeric validation as the factory. bootstrapExpressApplication(...) and runExpressApplication(...) also accept cors, globalPrefix, globalPrefixExclude, middleware, multipart, nativeMiddleware, securityHeaders, forceExitTimeoutMs, shutdownSignals, and logger; they use the framework console logger by default for startup and shutdown diagnostics and honor an injected ApplicationLogger when provided.
Related Packages
@fluojs/runtime: Core framework runtime.@fluojs/platform-fastify: Alternative high-performance adapter.@fluojs/websockets: Real-time gateway support for Express.
Example Sources
packages/platform-express/src/adapter.test.ts- This package does not currently ship a dedicated
examples/platform-expressapp. Use the Quick Start and native middleware scenario in this README for Express bootstrap shape andpackages/platform-express/src/adapter.test.tsfor executable Express adapter coverage, including native middleware ordering/termination/error propagation, SSE framing, native-route fallback parity, duplicate listen idempotency, retry exhaustion, startup retry cancellation during shutdown, idle keep-alive drain, and forced shutdown.examples/minimal/src/main.tsis Fastify-based and should not be treated as an Express example source.
