Before you start
- Node.js 22.13+ within the 22.x line, or Node.js 24, on a supported swm-uws platform: macOS arm64/x64, Windows x64, or Linux x64 glibc.
- Every example binds to loopback on port 3000. Stop the current process with Ctrl+C before starting the next recipe.
- Verification commands use Bash and curl. For SIGINT/SIGTERM and logger closure, move the recipe into the quick start’s ExampleService.
Prepare a directory
Run npm init -y in an empty directory, then install the pinned versions. Save code using the listed .mjs names; no ESM setting in package.json is needed.
npm install @swarmmachina/swm-core@5.2.3 @swarmmachina/swm-logs@0.1.1JSON API with CORS
Call the CORS helper before reading the body. For OPTIONS it handles the preflight and returns true; a regular POST gets CORS headers and a JSON response.
In the second terminal, expect 204 from preflight and {"received":{"ok":true}} from POST. The allowed origin is https://app.example. CORS controls browser access to responses; user authentication needs its own implementation.
import Server, { cors } from '@swarmmachina/swm-core'
const applyCors = cors({
origin: 'https://app.example',
methods: ['POST', 'OPTIONS'],
allowedHeaders: ['content-type'],
maxAge: 600
})
const server = new Server({
host: '127.0.0.1',
port: 3000,
ws: null,
http: {
maxBodySize: 64 * 1024,
maxBodyBudget: 8 * 1024 * 1024,
routes: [
{
method: 'any',
path: '/api/echo',
handler: async (ctx) => {
if (applyCors(ctx)) return
if (ctx.getMethod() !== 'post') {
ctx.setStatus(405)
return { error: 'Method not allowed' }
}
return { received: await ctx.json() }
}
}
]
}
})
await server.listen()node json-cors.mjs
# Second terminal:
curl -i -X OPTIONS http://127.0.0.1:3000/api/echo \
-H 'origin: https://app.example' \
-H 'access-control-request-method: POST' \
-H 'access-control-request-headers: content-type'
curl --fail http://127.0.0.1:3000/api/echo \
-H 'origin: https://app.example' \
-H 'content-type: application/json' --data '{"ok":true}'Authorize a WebSocket upgrade
A static DEMO_TOKEN demonstrates the authorization point for a server client. A missing token prevents startup; an incorrect token rejects the upgrade. prefetchHeaders explicitly retains the authorization header.
curl checks the handshake: expect 101 Switching Protocols with the correct token, or 403 without authorization. After a successful upgrade, curl exits at --max-time because the connection stays open.
The browser WebSocket API cannot set an arbitrary Authorization header. For browser clients, use your session mechanism and validate Origin. Replace the demo comparison with real authentication before exposing it over a network.
import Server from '@swarmmachina/swm-core'
const token = process.env.DEMO_TOKEN
if (!token) throw new Error('Set DEMO_TOKEN before starting the example')
const server = new Server({
host: '127.0.0.1',
port: 3000,
http: null,
ws: {
prefetchHeaders: ['authorization'],
upgradeTimeoutMs: 5_000,
maxPayloadLength: 16 * 1024,
maxBackpressure: 64 * 1024,
closeOnBackpressureLimit: true,
onUpgrade: (meta) => {
if (meta.url() !== '/ws') return null
return meta.headers.authorization === `Bearer ${token}` ? { role: 'demo' } : null
},
onMessage: (ctx, message) => ctx.send(ctx.decode(message))
}
})
await server.listen()DEMO_TOKEN=local-demo node websocket-auth.mjs
# Second terminal:
curl --http1.1 --max-time 2 -i http://127.0.0.1:3000/ws \
-H 'connection: Upgrade' -H 'upgrade: websocket' \
-H 'sec-websocket-version: 13' \
-H 'sec-websocket-key: dGhlIHNhbXBsZSBub25jZQ==' \
-H 'authorization: Bearer local-demo'Stream an upload to a file
Save both files together. UploadSink owns the active-upload counter: two streams are admitted, and additional requests receive 503. Each file gets a random name; a failed upload removes its partial file.
bodyStream() starts before the first await and feeds pipeline(). Prefetch is disabled, and each upload is capped at 8 MiB. The check returns 201 and the id of the file saved under ./uploads.
Streaming bypasses maxBodyBudget. The concurrency cap applies to this process only. Set storage capacity, user quotas, and cleanup of successful uploads separately.
import { randomUUID } from 'node:crypto'
import { createWriteStream } from 'node:fs'
import { rm } from 'node:fs/promises'
import { join } from 'node:path'
import { pipeline } from 'node:stream/promises'
export default class UploadSink {
#directory
#active = 0
constructor(directory) {
this.#directory = directory
}
async accept(ctx) {
if (this.#active >= 2) {
ctx.setStatus(503)
return { error: 'Upload capacity reached' }
}
const upload = ctx.bodyStream()
const id = randomUUID()
const path = join(this.#directory, id)
this.#active += 1
try {
await pipeline(upload, createWriteStream(path, { flags: 'wx' }))
ctx.setStatus(201)
return { id }
} catch (error) {
await rm(path, { force: true })
throw error
} finally {
this.#active -= 1
}
}
}import { mkdir } from 'node:fs/promises'
import Server from '@swarmmachina/swm-core'
import UploadSink from './upload-sink.mjs'
await mkdir('./uploads', { recursive: true })
const uploads = new UploadSink('./uploads')
const server = new Server({
host: '127.0.0.1',
port: 3000,
ws: null,
http: {
prefetch: false,
maxStreamBodySize: 8 * 1024 * 1024,
routes: [{ method: 'post', path: '/upload', handler: (ctx) => uploads.accept(ctx) }]
}
})
await server.listen()node upload.mjs
# Second terminal:
curl --fail http://127.0.0.1:3000/upload --data-binary @upload.mjsRequest IDs and structured logs
Generate requestId on the server, bind it to a child logger, and return it as x-request-id. This example logs only the method and path; it never logs bodies, cookies, or incoming credentials.
curl shows the same requestId in the header and JSON response. The server terminal emits an NDJSON record with that value. Redaction covers top-level authorization and password; nested fields need their own paths.
import { randomUUID } from 'node:crypto'
import Server from '@swarmmachina/swm-core'
import Logger from '@swarmmachina/swm-logs'
const logger = new Logger({
bindings: { service: 'api' },
redact: ['authorization', 'password']
})
const server = new Server({
host: '127.0.0.1',
port: 3000,
ws: null,
http: {
onRequest: (ctx) => {
const requestId = randomUUID()
const log = logger.child({ requestId })
ctx.setHeader('x-request-id', requestId)
log.info({ method: ctx.getMethod(), path: ctx.getUrl() }, 'request')
return { requestId }
}
}
})
await server.listen()node request-logging.mjs
# Second terminal:
curl -i http://127.0.0.1:3000/hello