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

@cogs/serialize-request

v0.2.0

Published

A utility function to serialize a request object in a way that's friendly to loggers, view engines, and converting to JSON

Readme

@cogs/serialize-request

Utility helpers for turning any inbound request into a logger-friendly JSON snapshot. Works with Next.js Request objects, the standard Fetch API Request, Node's IncomingMessage, or plain objects you shape yourself. The snapshotter normalizes IDs, methods, URLs, headers, and route metadata so observability pipelines receive a consistent payload regardless of runtime.

Why it exists

  • Predictable log payloads – Normalize x-request-id, uppercase methods, and trim long URLs so structured logs stay readable.
  • Header safety – Only include headers from a configurable allowlist (ignoring cookies/authorization by default) or pass an explicit whitelist for sensitive APIs.
  • Route + params support – Serializes route.path/params shapes used by Next middleware/route handlers without extra glue code.
  • Primitive fallback – If you pass a string/number/boolean, it still returns a well-formed { id, method, url, headers } object.

Anywhere you currently hand-build request metadata—middleware, API routes, instrumentation hooks, worker crash handlers—you can drop in serializeRequest() and ship an identical JSON shape.

import serializeRequest from "@cogs/serialize-request"

const serialized = serializeRequest(request, {
  includeHeaders: ["x-request-id", "user-agent", "content-type"],
})

log.info("middleware handling request", {
  request: serialized,
  routeType,
  isAuthenticated: request.auth != null && request.auth.error == null,
})

Adding that ahead of your existing log calls yields consistent payloads:

{
  "request": {
    "id": "abc123",
    "method": "GET",
    "url": "/environments/42",
    "headers": {
      "x-request-id": "abc123",
      "user-agent": "…",
      "content-type": "application/json"
    },
    "route": {
      "path": "/api/environments/[id]",
      "params": { "id": "42" }
    }
  },
  "routeType": "api",
  "isAuthenticated": true
}

No more duplicating header filtering or ID extraction; just call the helper and log the request field wherever you need it.

API surface

serializeRequest(request, options?)

Returns a normalized snapshot:

  • id – resolved from x-request-id header (or null if absent).
  • method – uppercased string, falls back to "-".
  • url – path + query, truncated when it grows unwieldy (default 200 characters).
  • headers – subset of allowed headers; defaults to a safe internal list and can be overridden via includeHeaders.
  • route{ path, params } when those properties exist on the incoming object (useful for Next's route metadata).

Options:

  • includeHeaders?: string[] – additional header names to whitelist. Values are normalized to lowercase internally.

Observability helpers

The package also exports helpers that pair neatly with loggers:

  • captureRequestSnapshot(request, options?) – Runs serializeRequest() (merging the built-in headers with the inlined safe-meta-header allowlist) and caches the snapshot on globalThis. Returns the serialized object so you can log it immediately.
  • getLastRequestSnapshot() – Read the most recently captured snapshot (used by crash handlers to include request metadata in fatal logs).
  • REQUEST_SNAPSHOT_HEADER_WHITELIST – Read-only list of headers captured by default, useful for documentation or downstream validation.

Usage ideas

  1. Middleware logging – replace ad-hoc header lookups with captureRequestSnapshot() to ensure every info/warn/error has identical request metadata.
  2. API routes – call const logBase = { request: captureRequestSnapshot(request) } once and spread it into every logger call.
  3. Crash handlers – call captureRequestSnapshot() when a request enters your system; later, use getLastRequestSnapshot() inside uncaughtException and unhandledRejection listeners to add the context automatically.
  4. View engines / SSR – pass the serialized object into your template renderer or monitoring hooks without worrying about non-serializable headers.