Node Server
@miiajs/node-server provides a high-performance Node.js HTTP server adapter for MiiaJS.
Installation
bun add @miiajs/node-server
npm install @miiajs/node-server
pnpm add @miiajs/node-server
yarn add @miiajs/node-server
Usage
import { Miia } from '@miiajs/core'
import { serve } from '@miiajs/node-server'
const app = new Miia().register(AppModule)
await app.listen(3000, serve)
With custom hostname:
await app.listen(3000, 'localhost', serve)
How it works
The serve function bridges Node.js's http.IncomingMessage/http.ServerResponse and the Web Standard Request/Response API that MiiaJS uses internally.
Performance modes
The adapter supports two modes:
Optimized mode (default)
Minimizes allocations on the hot path:
- Lazy Request Proxy - lightweight object instead of
new Request(). Method, URL, headers, and body are resolved only on first access. - Lightweight Headers - linear scan over raw header pairs instead of constructing a
Headersobject. Covers.get(),.has(),.forEach(), and iterators. - Body Buffering - small bodies (Content-Length ≤
bufferThreshold, any method but GET and HEAD) are buffered and parsed directly, bypassingReadableStreamandRequestcreation. Large or chunked bodies fall back to streaming. - LightResponse Cache - simple responses (string, null, Uint8Array) store a
[status, body, headers]tuple without creating a realResponseobject. - Sync Fast Path - a synchronous handler on a route without middleware, guards or schemas bypasses
Promiseallocation entirely.
Native mode
Full Web API compliance with standard Request and Response objects:
import { serve } from '@miiajs/node-server'
const server = await serve({
fetch: app.fetch,
port: 3000,
mode: 'native',
})
Use native mode when you need strict instanceof Response checks or run multiple frameworks in the same process.
The body is read once
In both modes the request body behaves as on a real Request, and as on Bun and Deno: one consumer gets it. Once ctx.json() / ctx.text() or any of ctx.req.json(), text(), arrayBuffer(), bytes(), blob() or formData() has taken the body, or ctx.req.body has been read, the next consumer rejects with TypeError: Body is unusable: Body has already been read, ctx.req.bodyUsed is true, and ctx.req.clone() throws. Clone the request before the first read if two consumers need the body. ctx.json() and ctx.text() still share their one read.
A response written while the request body is still unread goes out with Connection: close: the unread bytes stay on the socket, so the connection cannot carry another request.
A streamed body that the handler cancels is the exception - any body in native mode, and in optimized mode a chunked one or one over bufferThreshold. After ctx.req.body.cancel(), or a cancel of a stream derived from it, the adapter stops reading and the response goes out on the open connection. The rest of the body is then read and dropped, so the connection can carry the next request; a rest that takes longer than 500 ms or runs past 64 MB has its connection destroyed.
The URL of the Request is built from the request line and the Host header. A Host that is more than host[:port] or [IPv6]:port - one with a path, a query, a fragment, userinfo or a backslash in it - is not taken into it, so it cannot move the request to another route: the URL is built on localhost instead, as it is for a Host that makes no valid URL, and an empty Host gives the address the server listens on. A TRACE, which fetch forbids a Request to carry, is answered with a 501 without reaching the app (Node itself answers TRACK with a 400 and leaves CONNECT to the server's connect event). Optimized mode hands a TRACE to the app, as Bun and Deno do.
Standalone usage
The adapter can be used without the MiiaJS framework:
import { serve } from '@miiajs/node-server'
const server = await serve({
fetch: (req) => new Response('Hello, World!'),
port: 3000,
hostname: '0.0.0.0',
})
// Later...
await server.close()
Options
interface ServeOptions {
fetch: (req: Request) => Response | Promise<Response> // Required
port?: number // Default: 3000
hostname?: string // Default: '0.0.0.0'
mode?: 'optimized' | 'native' // Default: 'optimized'
bufferThreshold?: number // Default: 102400 (100KB)
maxBodySize?: number | false // Default: 1048576 (1MB)
logger?: { error(message: string, trace?: string, context?: string): void } // Default: console
}
The logger receives what the fetch handler throws or rejects with, which the adapter answers with a 500. app.fetch answers its own errors, so under Miia this is rare; app.listen(port, serve) passes the app's logger all the same.
The bufferThreshold controls the body buffering optimization in optimized mode. Bodies of any method but GET and HEAD with a known Content-Length up to this size are buffered in memory for fast json()/text() access. Bodies without Content-Length or larger than the threshold are streamed.
The maxBodySize caps request bodies. A request whose declared Content-Length exceeds the cap gets an immediate 413 JSON response - the handler never runs. The connection stays open while the adapter reads and drops the rest of the body, so it can carry the next request once the body is through; a body that takes longer than 500 ms or runs past 64 MB has its connection destroyed. Closing the connection right after the 413 instead would reset it under a client still uploading, and the reset can take the 413 with it. Chunked bodies (no Content-Length) are capped in-stream: the body stream rejects with an Error named 'PayloadTooLargeError', which @miiajs/core maps to a 413 automatically. Non-Miia consumers should catch this error by name. Pass false to disable the cap.
When used via app.listen(port, serve), Miia passes its computed ceiling (max of maxBodySize and all @BodyLimit values) automatically. To override it for the adapter, wrap the call:
await app.listen(3000, (info) => serve({ ...info, maxBodySize: 5 * 1024 * 1024 }))
ServerHandle
The serve function returns a ServerHandle with a close() method:
const server = await serve({ fetch: handler, port: 3000 })
// Graceful shutdown
await server.close()
close() is server.close() of node:http: it stops accepting connections, closes idle keep-alive connections at once and resolves once the requests in flight are done. A keep-alive connection that is busy with a request when close() is called stays open after its response until keepAliveTimeout runs out (5 s, plus the second Node adds to it) or the client closes it, and holds close() that long. A response that has been written but still sits in Node's buffer for a slow client when close() is called can be cut off. A connection still draining the body of a refused upload (see maxBodySize) when close() is called is busy too: if the rest of the body gets through, the connection is kept alive and holds close() until keepAliveTimeout runs out like any other busy one (about 6 s with the defaults, measured); if it does not get through within 500 ms, or runs past 64 MB, the connection is destroyed then.
Testing
@miiajs/node-server is exercised directly - serve() accepts any (req: Request) => Response | Promise<Response>, so you don't need a Miia instance to test it.
import { afterEach, expect, it } from 'bun:test'
import { serve, type ServerHandle } from '@miiajs/node-server'
let server: ServerHandle
afterEach(async () => {
if (server) await server.close()
})
it('handles GET requests', async () => {
server = await serve({
port: 18234,
fetch: () => Response.json({ ok: true }),
})
const res = await fetch('http://localhost:18234/')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ ok: true })
})
For applications that wire the adapter through app.listen(port, host, serve), prefer the TestApp pattern from Testing - it runs handlers without binding a port and works under any runtime.