Before you start
- Node.js 22.13+ within the 22.x line, or Node.js 24. swm-logs 0.1.1 does not yet support Node.js 26.
- macOS arm64/x64, Windows x64, or Linux x64 with glibc. The native transport does not support Alpine/musl or Linux ARM64.
- The example uses native ESM. The .mjs files work without changing the package.json type field.
Install the packages
Create a separate directory. Versions are pinned to keep the example reproducible. swm-core installs its native swm-uws transport as a dependency.
mkdir swm-quick-start
cd swm-quick-start
npm init -y
npm install @swarmmachina/swm-core@5.2.3 @swarmmachina/swm-logs@0.1.1Create the service
Save this as service.mjs. ExampleService owns Server and the root Logger. stop() returns one shared promise, so another signal does not start a second shutdown.
The JSON reader starts immediately inside the handler, before the first await. Anonymous WebSocket connections are accepted only on /ws; the server binds to loopback. This is a local learning endpoint.
import { randomUUID } from 'node:crypto'
import Server from '@swarmmachina/swm-core'
import Logger from '@swarmmachina/swm-logs'
export default class ExampleService {
#server
#logger
#stopPromise
constructor({ port = 3000 } = {}) {
this.#logger = new Logger({ bindings: { service: 'quick-start' } })
this.#server = new Server({
host: '127.0.0.1',
port,
http: {
maxBodySize: 64 * 1024,
maxBodyBudget: 8 * 1024 * 1024,
requestTimeoutMs: 10_000,
onError: (event, error) => this.#logger.error({ err: error, path: event.url }),
routes: [
{ method: 'get', path: '/health', handler: () => ({ ok: true }) },
{
method: 'post',
path: '/echo',
handler: async (ctx) => {
const log = this.#logger.child({ requestId: randomUUID() })
const body = await ctx.json()
log.info('echo received')
return { received: body }
}
}
]
},
ws: {
maxPayloadLength: 16 * 1024,
maxBackpressure: 64 * 1024,
closeOnBackpressureLimit: true,
onUpgrade: (meta) => (meta.url() === '/ws' ? {} : null),
onMessage: (ctx, message) => ctx.send(ctx.decode(message)),
onError: (_ctx, error) => this.#logger.error(error)
}
})
}
async start() {
await this.#server.listen()
this.#logger.info('HTTP and WebSocket ready on 127.0.0.1')
}
stop() {
this.#stopPromise ??= this.#shutdown()
return this.#stopPromise
}
async #shutdown() {
try {
await this.#server.shutdown(5_000)
} finally {
await this.#logger.close()
}
}
}Start the process
Save main.mjs beside service.mjs. On SIGINT or SIGTERM, the server gets up to five seconds to finish requests and connections, then the logger closes.
import ExampleService from './service.mjs'
const service = new ExampleService()
try {
await service.start()
for (const signal of ['SIGINT', 'SIGTERM']) {
process.once(signal, () => {
void service.stop().catch((error) => {
console.error(error)
process.exitCode = 1
})
})
}
} catch (error) {
console.error(error)
process.exitCode = 1
await service.stop()
}node main.mjsCheck HTTP and WebSocket
Save the check as check-websocket.mjs and run these commands in a second terminal. The built-in Node.js WebSocket client needs no extra package.
Expected results: /health returns {"ok":true}, /echo returns your object inside received, and the WebSocket prints hello. The first terminal emits NDJSON records with service context and a requestId.
const socket = new WebSocket('ws://127.0.0.1:3000/ws')
const deadline = setTimeout(() => {
socket.close()
process.exitCode = 1
}, 5_000)
socket.addEventListener('open', () => socket.send('hello'))
socket.addEventListener('message', (event) => {
console.log(event.data)
clearTimeout(deadline)
socket.close()
})
socket.addEventListener('error', () => {
clearTimeout(deadline)
process.exitCode = 1
})curl --fail http://127.0.0.1:3000/health
curl --fail http://127.0.0.1:3000/echo \
-H 'content-type: application/json' \
--data '{"hello":"world"}'
node check-websocket.mjsTake the next step
Stop the process with Ctrl+C. Before exposing a network service, add user and Origin checks during WebSocket upgrade, terminate TLS at a reverse proxy, and tune limits for your workload.
- This example allows up to 64 KiB per request body, an 8 MiB aggregate body budget, and a 10-second request timeout.
- WebSocket messages are capped at 16 KiB, with a 64 KiB outbound queue limit and slow-client closure at the limit.
- The logger closes after the server. The application owns delivery to external storage and its shutdown deadline.