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

@worknice/instrumentation

v1.68.0

Published

Shared instrumentation management for Worknice applications

Readme

@worknice/instrumentation

Shared instrumentation, logging and correlation ID management for Worknice applications.

Features

  • 🔍 Correlation ID Tracking: Request tracing across async boundaries using Node.js AsyncLocalStorage
  • 📝 Flushable Logging: Winston loggers that ship to Axiom and the console, and can be drained before a serverless instance freezes
  • 📊 Next.js Instrumentation: Error reporting with Axiom
  • 🔄 Cross-Service Tracing: Track requests across services (Notebook, MYOB, Micropay, Basics)

Installation

This package is part of the Worknice monorepo and is automatically available to all apps:

pnpm add @worknice/instrumentation

Getting Started

App Instrumentation

For Next.js apps, create an instrumentation.ts file in the app root:

// apps/$app-name/instrumentation.ts
export { register, onRequestError } from "@worknice/instrumentation";
  • register() - Initialises instrumentation. Automatically called by Next.js when instrumentation is enabled.
  • onRequestError() - Handles and logs request errors with correlation tracking. Automatically called by Next.js on errors.

Correlation ID Usage

The package provides multiple ways to work with correlation IDs:

Getting the current correlation ID

import { getCorrelationId } from "@worknice/instrumentation";

const correlationId = getCorrelationId();

Running code with a specific correlation ID

import { runWithCorrelationId, getCorrelationId } from "@worknice/instrumentation";

await runWithCorrelationId("$correlationId", async () => {
  // All async operations here will have access to the correlation ID
  const id = getCorrelationId(); // Returns "$correlationId"
});

Getting or generating a correlation ID

import { getOrGenerateCorrelationId } from "@worknice/instrumentation";

const { correlationId, isNew } = getOrGenerateCorrelationId();

Extracting from HTTP headers

Extract correlation ID from HTTP headers in order:

  • x-request-id
  • x-correlation-id
  • request-id
  • correlation-id
import { extractCorrelationIdFromHeaders } from "@worknice/instrumentation";

const correlationId = extractCorrelationIdFromHeaders(request.headers);

Logging

createLogger builds a Winston logger that writes to Axiom and the console, stamps every entry with the current correlation ID, and can be flushed on demand. It is imported from the /logger subpath, not from the package root — see Package layout and the Edge runtime.

// apps/$app-name/src/services/logger.ts
import createLogger from "@worknice/instrumentation/logger";

import config from "@/config";

const logger = createLogger({
  axiom: config.axiom,
  defaultMeta: {
    host: config.baseUrl.hostname,
  },
});

export default logger;

Options:

  • axiom — { dataset, token }. The Axiom transport is only attached when both are present.
  • defaultMeta — merged into every entry.
  • level — defaults to debug.

The returned FlushableLogger is a winston.Logger with an added flush(). The console transport is always attached, so entries reach Vercel's log drain even when Axiom is unconfigured or a delivery fails.

Flushing

The Axiom transport batches entries in memory and ships them about a second after the first one arrives. Serverless instances are frozen as soon as the response is returned, so on a fast request — an early error, typically — that batch is discarded before it is ever sent. flush() drains Winston's internal stream and then waits for the transport to deliver. That includes any ingest request the transport had already started on its own timer, which would otherwise still be on the wire when the instance freezes.

Loggers built by createLogger register themselves in a process-wide registry, so generic code can drain them all without knowing what they are:

import { flushLogs } from "@worknice/instrumentation";

await flushLogs();

You rarely need to call this yourself. Three seams already flush for you, covering the ways an invocation normally ends:

| Seam | Covers | | --- | --- | | handleRequest in @worknice/js-sdk | Webhook and API route handlers | | withServerAction | Server actions, including ones that throw or redirect() | | onRequestError | Errors that reach Next.js uncaught |

Only the first and third are automatic. Server actions get the seam by being wrapped, which is worth doing to every one of them rather than only the ones that log — both halves are cheap when there is nothing to do, and an unwrapped action fails silently:

import { withServerAction } from "@worknice/instrumentation";

export const saveConfig = withServerAction(async (config: Config) => {
  // Correlation context is established, and buffered logs are shipped on the way out.
});

Work that outlives the response is not covered, because it runs after those seams have already flushed. Drain it yourself:

after(async () => {
  try {
    await doDeferredWork();
  } finally {
    await flushLogs();
  }
});

The same applies to waitUntil callbacks and any promise you deliberately don't await.

registerLogSink is available for loggers not built by this factory. It takes a { flush: () => Promise<void> } and returns an unregister function.

Configuration

Environment Variables

The package supports the following environment variables:

  • AXIOM_DATASET: Axiom dataset name for error logging
  • AXIOM_TOKEN: Axiom API token for authentication
  • NODE_ENV: Environment name (development, staging, production)

These are read directly by onRequestError. Loggers you build with createLogger take their credentials from the axiom option instead, so apps keep passing them through their own config.

When Axiom credentials are not provided, entries still go to the console and flush() becomes a no-op. The console transport is not a fallback: it is always attached, so logs go to both destinations whenever Axiom is configured.

Architecture

AsyncLocalStorage

The package uses Node.js AsyncLocalStorage to maintain correlation context across async boundaries without explicitly passing IDs through function calls. This allows correlation IDs to automatically flow through:

  • GraphQL operations
  • Database queries
  • API calls
  • Background jobs
  • Nested async operations

Package layout and the Edge runtime

Every app's src/middleware.ts imports this package and runs on the Edge runtime, which has no node:async_hooks, no streams and no Winston. Everything reachable from src/index.ts therefore has to be Edge-safe at module scope, which is why:

  • correlation.ts imports node:async_hooks lazily, inside a function.
  • instrumentation.ts is a thin shim whose register/onRequestError dynamically import the Node-only instrumentation-node.ts.
  • logSinks.ts has no imports at all. That's what lets serverAction.ts drain Winston loggers without importing Winston.

logger.ts imports winston and @axiomhq/winston at module scope and cannot follow those patterns, so it is reached only through its subpath and is deliberately absent from src/index.ts.

⚠️ Don't re-export logger.ts from src/index.ts. A convenience line like export { default as createLogger } from "./logger.js"; pulls Winston into the module graph of every consumer of the package root — including middleware.ts. Nothing locally will warn you: the barrel type-checks, tests pass, and Node routes run fine. It surfaces as an Edge bundling failure or a bloated middleware bundle at build time, in a file nobody touched.

The rule for anything added here: a module that imports a Node-only dependency at module scope stays out of src/index.ts and is consumed via its subpath. The "./*" entry in exports already makes every module importable that way, so no packaging change is needed.

Development

Building

pnpm --filter=@worknice/instrumentation build

Development Mode

pnpm --filter=@worknice/instrumentation dev

Testing & Linting

pnpm --filter=@worknice/instrumentation test:lint
pnpm --filter=@worknice/instrumentation test:types
pnpm --filter=@worknice/instrumentation test:format

Use Cases

Cross-Service Request Tracing

When a request flows through multiple services (e.g., Notebook → MYOB → External API), the correlation ID helps trace the entire request chain:

In Notebook app:

import { getOrGenerateCorrelationId } from "@worknice/instrumentation";

const { correlationId } = getOrGenerateCorrelationId();
await fetch("https://myob-service/api/endpoint", {
  headers: {
    "x-correlation-id": correlationId,
  },
});

In MYOB service:

import { extractCorrelationIdFromHeaders, runWithCorrelationId } from "@worknice/instrumentation";

const correlationId = extractCorrelationIdFromHeaders(req.headers);
runWithCorrelationId(correlationId, async () => {
  // All operations here share the same correlation ID
  await processRequest();
});

Background Job Tracking

Track background jobs initiated from web requests:

In API route:

import { getCorrelationId } from "@worknice/instrumentation";

const correlationId = getCorrelationId();
await inngest.send({
  name: "process.data",
  data: { correlationId, ...payload },
});

In Inngest function:

import { runWithCorrelationId } from "@worknice/instrumentation";

export const processData = inngest.createFunction(
  { id: "process-data" },
  { event: "process.data" },
  async ({ event }) => {
    return runWithCorrelationId(event.data.correlationId, async () => {
      // Job execution with correlation tracking
    });
  }
);

Troubleshooting

Correlation ID Not Available

If getCorrelationId() returns undefined:

  1. Ensure you're within a correlation context (use runWithCorrelationId)
  2. Verify the context hasn't been lost (e.g., through setTimeout without binding)

Axiom Logs Not Appearing

  1. Verify AXIOM_DATASET and AXIOM_TOKEN environment variables are set
  2. Check console output on startup for "Axiom error logging enabled" message
  3. Ensure the Axiom dataset exists and token has write permissions
  4. Check whether the entries reached Vercel's logs. Everything is written to the console too, so if they are in Vercel but not Axiom, it's a delivery problem — look for [Logger] Axiom rejected a batch of logs.
  5. If they are in neither, the entry probably never reached a logger built by createLogger. Check that the code path passes the app's logger rather than falling back to console — handleRequest does this when no logger option is given

Logs Missing Only From Failed Or Fast Requests

The batch was almost certainly discarded when the instance froze. Check that the code path ends at one of the three flushing seams (handleRequest, withServerAction, onRequestError). Work scheduled with after() or waitUntil, or a promise that isn't awaited, runs past those seams and needs its own await flushLogs().