Packages / uWS Server

uWS Server

uWebSockets.js HTTP server adapter for maximum throughput.

@miiajs/uws-server provides a high-performance HTTP server adapter using uWebSockets.js - a C++ networking library that is significantly faster than Node.js's built-in http module.

Installation

bun add @miiajs/uws-server

Runs on Node.js 22, 24 and 26 only: uWebSockets.js ships native binaries for those lines and does not load on Bun or Deno.

uWebSockets.js comes with the adapter as its dependency, pinned to a GitHub release - the official build is not published to npm, so there is nothing to install next to it. Do not add uWebSockets.js from the npm registry yourself: anything published there under that name is not the official build.

Usage

typescript
import { Miia } from '@miiajs/core'
import { serve } from '@miiajs/uws-server'

const app = new Miia().register(AppModule)

await app.listen(3000, serve)

With custom hostname:

typescript
await app.listen(3000, '0.0.0.0', serve)

How it works

The adapter converts uWebSockets.js request/response objects to the Web Standard Request/Response API that MiiaJS expects. Since uWS HttpRequest is only valid synchronously, all metadata (method, URL, headers) is captured before any async gap.

The client address in ctx.conn.remoteAddress (and ctx.ip without trustProxy) is the text uWS gives, so an IPv6 address comes in full form: 0000:0000:0000:0000:0000:0000:0000:0001 rather than the ::1 of node-server, Bun and Deno, and 0000:0000:0000:0000:0000:ffff:7f00:0001 for an IPv4 client of a dual-stack listener. Rate-limit keys and IP allow lists for clients that connect directly over IPv6 therefore differ from the other adapters. Behind a proxy with trustProxy set, ctx.ip comes from the proxy's header and is not affected.

Large request bodies are bridged to a ReadableStream and read at the handler's pace: once the stream's queue passes bodyHighWaterMark the socket is paused, and it resumes as the handler drains. A slow storage target therefore slows the upload down instead of filling memory. Small bodies with a declared Content-Length never reach that path in optimized mode - uWS accumulates them natively in C++. In mode: 'native' every body is streamed.

Performance 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 header pairs instead of constructing a Headers object. uWS provides lowercase keys natively, so lookups are direct string comparisons.
  • Body Buffering - small bodies (Content-Length ≤ bufferThreshold, any method but GET and HEAD) are buffered and parsed directly, bypassing ReadableStream and Request creation. Large or chunked bodies fall back to streaming.
  • LightResponse Cache - simple responses (string, null, Uint8Array) store a [status, body, headers] tuple without creating a real Response object.
  • Corked Writes - batches header + body writes into a single syscall via res.cork().
  • Sync Fast Path - a synchronous handler on a route without middleware, guards or schemas bypasses Promise allocation entirely.

Native mode

typescript
const server = await serve({
  fetch: app.fetch,
  port: 3000,
  mode: 'native',
})

Full Web API compliance with standard Request and Response objects. Use when strict spec conformance is needed. Native mode buffers no body: every request body is streamed, whatever its size.

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 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. A method a Request cannot carry - TRACE, TRACK and CONNECT, which fetch forbids - is answered with a 501 without reaching the app, and a method that is not a valid token with a 400. Optimized mode hands both to the app, as Bun and Deno do.

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.

Standalone usage

typescript
import { serve } from '@miiajs/uws-server'

const server = await serve({
  fetch: (req) => new Response('Hello, World!'),
  port: 8080,
})

await server.close()

Shutdown

close() on the handle stops listening, then resolves once every request in flight has its response out - a streamed response included, and a request that arrives on a kept-alive connection in the meantime too. Then it closes every connection that is left, kept-alive ones included, so nothing is served after it has resolved.

Out means handed to uWS: a body in memory goes out through one res.end() and counts as out at once, a streamed body is written at the client's pace as the socket takes it - in pieces of up to 64 KB when the response declares no Content-Length. What can still sit in uWS's own buffer at that point is whatever the socket has not taken of a body in memory - most of it, for a large body and a slow client - or the rest of the last piece of a stream. The connections are closed at once all the same, so a client too slow to have taken that rest by then gets its response cut off; a client that keeps up gets all of it. A large response that has to outlive a shutdown for a slow client goes out as a stream. A request whose client has gone away no longer counts.

There is no timeout: a handler that never answers keeps close() pending, and so does an endless stream such as server-sent events, until it ends or its client goes away. Under app.listen(port, serve) this is what lets a SIGTERM finish the requests in flight before the shutdown hooks run.

Options

typescript
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)
  bodyHighWaterMark?: number // Default: 262144 (256KB)
  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 use ReadableStream for streaming.

The bodyHighWaterMark is how many bytes a streamed request body may queue before the socket is paused; it resumes as the handler drains the stream, so the client uploads at the handler's pace instead of filling memory. It applies to the streaming path only - buffered bodies are bounded by bufferThreshold by construction. Values must be integers of at least 1; anything else makes serve() reject.

While a response write is itself waiting for a slow client, the socket keeps reading so the write can finish; a request body that piles up past twice bodyHighWaterMark unread in that time is given up - its stream errors, and what still arrives is dropped.

The pause is advisory: uSockets keeps reading from the socket until the kernel runs dry inside one poll event, so the queue overshoots by whatever the client already had in flight - measured at 1.4 MB after a pause that fired at 16 KB. Size capacity against bodyHighWaterMark plus roughly 1.5 MB resident per concurrent upload. Measured at 64 KB, 256 KB and 1 MB, the value made no difference to throughput on a single 160 MB upload or on ten concurrent ones, so the default sits in the middle of a flat range - very small values buy nothing but pause/resume churn.

bodyHighWaterMark is not reachable through app.listen(port, serve): Miia passes a fixed set of options to the adapter callback, and this is not one of them. Wrap the call to set it, the same way maxBodySize is overridden below:

typescript
await app.listen(3000, (info) => serve({ ...info, bodyHighWaterMark: 1024 * 1024 }))

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 cannot carry another request until that body is through, so the answer says Connection: close. uWS discards whatever of the body still comes, and the client closes the connection as told; a client that sent only the headers and keeps the connection open is closed by uWS's idle timeout, about 10 s. A client that keeps writing a large body without reading can still lose the 413: node:http uploading 64 MB without Expect: 100-continue got a reset instead in a quarter to a half of the tries, with or without Connection: close, while fetch, curl and clients that wait for 100 Continue got the 413 every time (measured). 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:

typescript
await app.listen(3000, (info) => serve({ ...info, maxBodySize: 5 * 1024 * 1024 }))

When to use

Choose @miiajs/uws-server when:

  • Maximum throughput is critical
  • You're running on Node.js and need higher performance than the built-in http module
  • You're comfortable with native binary dependencies

Choose @miiajs/node-server when:

  • You prefer zero native dependencies
  • You need broader platform compatibility
  • Performance is sufficient with the Node.js adapter

On Bun and Deno, no adapter is needed - app.listen() auto-detects the runtime.

Testing

@miiajs/uws-server is exercised directly via serve(). Tests must run under Node.js - the native uWS binary does not load on Bun or Deno.

typescript
// node --experimental-strip-types --no-warnings --test
import { afterEach, describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { serve } from '@miiajs/uws-server'

let server: { close(): Promise<void> }

afterEach(async () => {
  if (server) await server.close()
})

it('handles GET requests', async () => {
  server = await serve({
    port: 19234,
    fetch: () => Response.json({ ok: true }),
  })

  const res = await fetch('http://localhost:19234/')
  assert.equal(res.status, 200)
  assert.deepEqual(await res.json(), { 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.

Edit this page on GitHub