npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sirena-lwm2m/coap

v0.10.1

Published

RFC 7252 CoAP server stack for Node.js (>= 24): UDP and TCP (RFC 8323) transports, DTLS/TLS secure transports, a router with middleware, block-wise transfers (RFC 7959), Observe (RFC 7641), pluggable transaction stores and OpenTelemetry metrics.

Readme

@sirena-lwm2m/coap

RFC 7252 CoAP server stack for Node.js (>= 24): UDP and TCP (RFC 8323) transports, DTLS/TLS secure transports, a router with middleware, block-wise transfers (RFC 7959), Observe (RFC 7641), pluggable transaction stores and OpenTelemetry metrics.

| Capability | Docs | |---|---| | UDP transport | udp-transport | | TCP transport (RFC 8323) | tcp-transport | | Secure transports | security | | Router and middleware | router | | Block-wise transfers | blockwise | | Observe | observe | | Transaction stores | store | | Observability | observability | | Full API | api-reference | | Contributing | mutation-testing, releasing |

Installation

npm install @sirena-lwm2m/coap

Quick start — UDP

import { createServer, Response, stringToBytes } from '@sirena-lwm2m/coap';

const server = createServer({
  listen: [{ host: '0.0.0.0', port: 5683 }],
});

server.on('request', async (req, ctx) => {
  await ctx.respond(Response.ok(stringToBytes(req.url)));
});

await server.start();
console.log('Listening on:', server.listenerSummary());

TCP transport (RFC 8323)

The server supports CoAP over TCP using the coap+tcp:// URI scheme. Bind one or more TCP listeners alongside UDP by passing URI strings to the listen array.

import { createServer, Response, stringToBytes } from '@sirena-lwm2m/coap';

const server = createServer({
  listen: [
    'coap://127.0.0.1:5683',     // UDP
    'coap+tcp://127.0.0.1:5684', // TCP (RFC 8323)
  ],
});

server.on('request', async (req, ctx) => {
  // ctx.transport is 'udp' or 'tcp'
  console.log(`[${ctx.transport}] ${req.url}`);
  await ctx.respond(Response.ok(stringToBytes(`hello via ${ctx.transport}`)));
});

await server.start();
console.log('Listening on:', server.listenerSummary());
await server.stop();

See examples/slice-2.ts for a working dual-transport demo.

See docs/tcp-transport.md for framing details, connection multiplexing, and configuration.

Secure transports (coaps:// and coaps+tcp://)

Breaking in 0.10.0: coaps:// is now DTLS 1.2 over UDP (RFC 7252 section 9). Earlier versions served it as TLS over TCP. For TLS over TCP use coaps+tcp://.

const server = createServer({
  listen: ['coaps://0.0.0.0:5684', 'coaps+tcp://0.0.0.0:5685'],
  security: { mode: 'psk', psk: (identity) => lookupKey(identity) }, // or { mode: 'x509', key, cert }
});
server.on('dtls-handshake', ({ peer, durationMs }) => { /* peer.mode: 'psk' | 'x509' */ });

Built-in DTLS provider: DTLS 1.2 server and client session; cipher suites TLS_PSK_WITH_AES_128_CCM_8, TLS_PSK_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; extended master secret; X.509 mode needs an EC (ECDSA) key; no resumption, renegotiation or DTLS 1.3. security.sessionCacheSize is deprecated and ignored.

Client DTLS over UDP:

import { DtlsClientSession } from '@sirena-lwm2m/coap';

const session = new DtlsClientSession({ psk: { identity, key } });
const flight = session.start(); // send flight.outgoing; feed peer packets to session.handleDatagram(buf)

MTU: a CoAP message sent over coaps:// may be at most dtlsMaxPayload bytes (default 1200, the whole message). DTLS does not fragment; larger sends fail with 'exchange-error', so use block-wise transfer for large bodies.

coaps+tcp:// is TLS over TCP (Node tls) and emits tls-handshake. If you used coaps:// for TLS over TCP before 0.10.0, switch to coaps+tcp://; see the migration notes in docs/security.md.

Replace the DTLS implementation with ServerOptions.dtlsProvider (a DtlsProvider factory returning a DtlsSocket). See the API reference.

Router and middleware

createApp (from @sirena-lwm2m/coap/router) attaches a radix-tree router to a server. Path templates use {name} parameters, available as ctx.params. discovery: true serves /.well-known/core. See docs/router.md and examples/slice-4.ts.

import { createServer, Response, stringToBytes } from '@sirena-lwm2m/coap';
import { createApp } from '@sirena-lwm2m/coap/router';

const server = createServer({ listen: ['coap://0.0.0.0:5683'] });
const app = createApp({ server, discovery: true });

app.use((req, ctx, next) => next()); // middleware
app.add({
  path: '/3/{iid}',
  method: 'GET',
  handler: async (_req, ctx) => {
    await ctx.respond(Response.ok(stringToBytes(`instance ${ctx.params?.iid}`)));
  },
});
await server.start();

Block-wise transfers (RFC 7959)

blockwiseMiddleware reassembles Block1 uploads and chunks Block2 downloads, so handlers see a whole body and respond once. See docs/blockwise.md and examples/slice-5-firmware.ts.

import { blockwiseMiddleware } from '@sirena-lwm2m/coap/blockwise';

app.use(blockwiseMiddleware({ maxBytes: 4 * 1024 * 1024, idleTimeoutMs: 10_000 }));

Observe (RFC 7641)

Call ctx.observe(observable) in a GET handler after responding; registered clients receive a notification for each value the Observable emits. See docs/observe.md and examples/slice-6-temperature.ts.

import { Response } from '@sirena-lwm2m/coap';
import type { Observable, Observer, Unsubscribe } from '@sirena-lwm2m/coap';

const observers = new Set<Observer<Uint8Array>>();
const temperature: Observable<Uint8Array> = {
  subscribe(o: Observer<Uint8Array>): Unsubscribe {
    observers.add(o);
    return () => { observers.delete(o); };
  },
};

app.add({
  path: '/temperature',
  method: 'GET',
  handler: async (_req, ctx) => {
    await ctx.respond(Response.ok(new Uint8Array([20])));
    ctx.observe(temperature); // no-op for non-Observe requests
  },
});
// later: for (const o of observers) o.next(new Uint8Array([21]));

Transaction stores

CON/NON de-duplication uses a TransactionStore; the default is in-memory. createSqliteStore (needs the optional better-sqlite3 package) makes it durable across restarts. See docs/store.md and examples/slice-7-file-store.ts.

import { createSqliteStore } from '@sirena-lwm2m/coap/store';

const store = await createSqliteStore({ path: './dedup.db' });
const server = createServer({ listen: ['coap://0.0.0.0:5683'], store });

Observability

ServerOptions.metrics takes a CoapMetrics. tryBindOtel lazily loads @opentelemetry/api and falls back to no-op instruments if it is absent. See docs/observability.md and examples/slice-7-otel.ts.

import { tryBindOtel } from '@sirena-lwm2m/coap/observability';

const metrics = await tryBindOtel('@sirena-lwm2m/coap');
const server = createServer({ listen: ['coap://0.0.0.0:5683'], metrics });

ExchangeContext

Every 'request' event handler receives a Request and an ExchangeContext:

interface ExchangeContext {
  remote: string;           // "ip:port" of the sender
  local: string;            // "ip:port" of the receiving socket
  transport: 'udp' | 'tcp'; // which transport delivered this request
  token: Uint8Array;        // CoAP token bytes
  messageId: number;        // CoAP message ID (0 for TCP)
  options: CoapOption[];    // raw parsed options
  peer: Peer;               // anonymous, or psk identity / x509 certChain
  respond(res: Response): Promise<void>;
  cancel(): void;
  abort(code: CoapCode): void;
}

License

MIT