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

@device-router/middleware-fastify

v0.4.0

Published

Fastify plugin for DeviceRouter — device classification and rendering hints per request

Readme

@device-router/middleware-fastify

Fastify middleware for DeviceRouter. Adds device classification and rendering hints to every request.

Installation

pnpm add @device-router/middleware-fastify @device-router/storage @fastify/cookie

For automatic probe injection:

pnpm add @device-router/probe

Quick start

import Fastify from 'fastify';
import cookie from '@fastify/cookie';
import { createDeviceRouter } from '@device-router/middleware-fastify';
import { MemoryStorageAdapter } from '@device-router/storage';

const app = Fastify();
const { middleware, probeEndpoint } = createDeviceRouter({
  storage: new MemoryStorageAdapter(),
});

await app.register(cookie);
await app.register(middleware);

app.post('/device-router/probe', probeEndpoint);

app.get('/', (req, reply) => {
  const profile = req.deviceProfile;

  if (profile?.hints.preferServerRendering) {
    return reply.send(renderSSR());
  }
  if (profile?.hints.deferHeavyComponents) {
    return reply.send(renderLite());
  }
  reply.send(renderFull());
});

app.listen({ port: 3000 });

How it works

  1. Probe endpoint receives device signals from the browser and stores a classified profile
  2. Middleware registers a preHandler hook that reads the session cookie, loads the profile from storage, and attaches it to req.deviceProfile
  3. Your route handlers use req.deviceProfile.hints and req.deviceProfile.tiers to adapt responses

Probe auto-injection

Automatically inject the probe <script> into HTML responses:

const { middleware, probeEndpoint, injectionMiddleware } = createDeviceRouter({
  storage: new MemoryStorageAdapter(),
  injectProbe: true,
  probeNonce: 'my-csp-nonce', // optional
});

When injectProbe is enabled, the middleware registers an onSend hook that injects the script before </head>.

Streaming responses: The onSend hook receives the serialized payload as a string. If you stream responses via reply.raw, the hook is bypassed and injection is skipped. Add the probe <script> tag to your HTML shell manually instead.

Custom thresholds

const { middleware, probeEndpoint } = createDeviceRouter({
  storage,
  thresholds: {
    cpu: { lowUpperBound: 4, midUpperBound: 8 },
    memory: { midUpperBound: 8 },
  },
});

Options

| Option | Type | Default | Description | | --------------------- | --------------------------------------------- | ----------------- | --------------------------------------------- | | storage | StorageAdapter | (required) | Storage backend for profiles | | cookieName | string | 'dr_session' | Session cookie name | | cookiePath | string | '/' | Cookie path | | cookieSecure | boolean | false | Set Secure flag on the session cookie | | ttl | number | 86400 (24h) | Profile TTL in seconds | | rejectBots | boolean | true | Reject bot/crawler probe submissions | | thresholds | TierThresholds | Built-in defaults | Custom tier thresholds (validated at startup) | | injectProbe | boolean | false | Auto-inject probe into HTML | | probePath | string | — | Custom probe endpoint path | | probeNonce | string \| ((req: FastifyRequest) => string) | — | CSP nonce for injected script | | fallbackProfile | FallbackProfile | — | Fallback profile for first requests | | classifyFromHeaders | boolean | false | Classify from UA/Client Hints | | onEvent | OnEventCallback | — | Observability callback for logging/metrics |

Observability

Pass an onEvent callback to receive events for classification, storage, bot rejection, and errors:

const { middleware, probeEndpoint } = createDeviceRouter({
  storage,
  onEvent: (event) => {
    console.log(`[device-router] ${event.type}`, event);
  },
});

See the Observability guide for details.

Exports

  • createDeviceRouter(options) — All-in-one setup returning { middleware, probeEndpoint, injectionMiddleware? }
  • createMiddleware(options) — Standalone preHandler hook
  • createProbeEndpoint(options) — Standalone probe endpoint handler
  • createInjectionMiddleware(options) — Standalone onSend injection hook

Compatibility

  • Fastify 5.x
  • @fastify/cookie 11.x
  • Node.js >= 20

License

MIT