Nostics
Api

Reference

API reference for nostics core exports, reporters, formatters, and plugins.

nostics

import {
  createConsoleReporter,
  defineDiagnostics,
  defineProdDiagnostics,
  Diagnostic,
  formatDiagnostic,
  mergeDiagnostics,
} from 'nostics'
import type { InferDiagnosticCodes } from 'nostics'

defineDiagnostics(options)

const diagnostics = defineDiagnostics({
  docsBase: code => `https://nuxt.com/e/${code.replace('NUXT_', '').toLowerCase()}`,
  reporters: [createConsoleReporter()],
  codes: {
    NUXT_B2011: {
      why: (p: { src: string, mode: 'client' | 'server' }) => {
        const expected = p.mode === 'client' ? 'server' : 'client'
        return `Plugin "${p.src}" is ${expected}-only but was registered with mode "${p.mode}".`
      },
      fix: (p: { mode: 'client' | 'server' }) => {
        const expected = p.mode === 'client' ? 'server' : 'client'
        return `Rename the file or register it with mode "${expected}".`
      },
    },
  },
})

Options:

FieldTypeRequiredDescription
codesRecord<string, DiagnosticDefinition>yesCode definitions
docsBasestring | ((code) => string | undefined)noBase docs URL or URL resolver
reportersDiagnosticReporter[]noReporters called on every diagnostic

Definition:

interface DiagnosticDefinition<
  P = any,
  Data extends Record<string, unknown> = Record<string, unknown>,
> {
  why: string | ((params: P) => string)
  fix?: string | ((params: P) => string)
  docs?: string | false
  data?: Data | ((params: P) => Data)
}

Call-site fields:

interface DiagnosticCallParams {
  cause?: unknown
  sources?: string[]
}

cause and sources are reserved param names: why, fix, and data functions cannot use them.

diagnostics.CODE.is(error)

Type guard for caught errors. It checks that error is a Diagnostic with the code of the handle and narrows error.data to the data of this code. It does not run reporters. To check for any diagnostic, use instanceof Diagnostic.

try {
  addRuntimePlugin(plugin)
}
catch (error) {
  if (diagnostics.NUXT_B2011.is(error)) {
    error.data // data of NUXT_B2011
    error.fix
  }
  else if (diagnostics.NUXT_B2012.is(error) || diagnostics.NUXT_B2013.is(error)) {
    error.data // data of NUXT_B2012 or NUXT_B2013
  }
  else if (diagnostics.is(error)) {
    error.code // 'NUXT_B2011' | 'NUXT_B2012' | ...
    if (error.code === 'NUXT_B2011') error.data // data of NUXT_B2011
  }
  else if (error instanceof Diagnostic) {
    error.name // any diagnostic
  }
}

diagnostics.is(error) checks that this registry instance created error (in the same JavaScript realm) and narrows error to a union of the diagnostics of all its codes: error.code is the union of codes, and a check on error.code narrows error.data. is is a reserved name, you cannot name a code is. If you rely on Object.keys(diagnostics), that only works with defineDiagnostics(), because defineProdDiagnostics() returns a Proxy that has no enumerable keys.

diagnostics.CODE.is(error) also checks that this registry created error. It does not use this, so you can pass it as a callback: errors.filter(diagnostics.NUXT_B2011.is).

defineProdDiagnostics(options?)

Lean production counterpart to defineDiagnostics. Returns a Proxy that builds a minimal Diagnostic for any accessed code: the code becomes the instance name, docs is derived from docsBase, and the message (why) points to the docs URL when one exists (empty otherwise, so the thrown header is just the code). It carries no catalog text or data, so it stays tiny in a bundle. Its data property is undefined.

const diagnostics = defineProdDiagnostics({
  docsBase: code => `https://nuxt.com/e/${code.replace('NUXT_', '').toLowerCase()}`,
})

throw diagnostics.NUXT_B2011() // Error: NUXT_B2011, docs derived from docsBase

Options:

FieldTypeRequiredDescription
docsBasestring | ((code) => string | undefined)noBase docs URL or URL resolver, identical to defineDiagnostics
reportersDiagnosticReporter[]noReporters called on every diagnostic. Omitted by default in production builds

Select it in production with a process.env.NODE_ENV ternary so bundlers drop the full catalog. See Production builds.

It has the same diagnostics.is(error) and diagnostics.CODE.is(error) type guards as defineDiagnostics. Because prod diagnostics have no data, is narrows error.data to undefined. On a dev/prod ternary, error.data is the data of the code or undefined.

InferDiagnosticCodes<typeof diagnostics>

Union of the codes of a registry. Use it instead of keyof typeof diagnostics.

import type { InferDiagnosticCodes } from 'nostics'

type DiagnosticCode = InferDiagnosticCodes<typeof diagnostics>
// 'NUXT_B2011' | 'NUXT_B2012' | ...

An untyped defineProdDiagnostics() gives string.

mergeDiagnostics(...registries)

Merges registries into one object with every code. Use it to export one object when you split a large catalog by domain.

export const diagnostics = mergeDiagnostics(buildDiagnostics, runtimeDiagnostics)

diagnostics.NUXT_B2011({ src, mode }) // same handle as buildDiagnostics.NUXT_B2011
diagnostics.is(error) // a diagnostic of any merged registry
buildDiagnostics.is(error) // only the build ones

The handles are the same functions as in the source registries, and InferDiagnosticCodes gives every code. On a duplicate code, the last registry wins.

It is for catalogs that ship in production too. So it accepts only defineDiagnostics() registries: a defineProdDiagnostics() registry is a type error.

Diagnostic

class Diagnostic<Data = undefined, Code extends string = string> extends Error {
  name: Code
  code: Code
  message: string
  get why(): string
  fix?: string
  docs?: string
  sources?: string[]
  cause?: unknown
  data: Data
  toJSON(): DiagnosticJSON<Data>
}

name and code are the code. Diagnostics from a registry have the literal code type (Diagnostic<Data, 'NUXT_B2011'>), so they stay assignable to Diagnostic<Data>. message and why are the resolved explanation. data is inferred for each code from its static object or resolver return type. toJSON() returns name, why, fix, docs, sources, cause, data, and stack.

When you call JSON.stringify(diagnostic), fields whose value is undefined are omitted from the JSON output.

instanceof Diagnostic matches any diagnostic but does not narrow data. To check for a code (or all the codes of a registry) and get typed data, use diagnostics.CODE.is(error) (or diagnostics.is(error)).

DiagnosticReporter

type DiagnosticReporter<Options extends object = {}, Data = any> = (
  diagnostic: Diagnostic<Data>,
  options: Options,
) => void

Use the second generic when a reporter handles a known data shape. Reporters shared by unrelated codes can leave it at the default.

formatDiagnostic(diagnostic)

Renders plain multiline text.

[NUXT_B2011] Plugin `./runtime/analytics.server.ts` is server-only but was registered with mode `client`.
├▶ fix: Rename the file or register it with mode `server`.
├▶ sources: modules/analytics.ts:18:5
╰▶ see: https://nuxt.com/e/b2011

createConsoleReporter

function createConsoleReporter(options?: {
  method?: 'log' | 'error' | 'warn' // default 'warn'
  formatter?: (diagnostic: Diagnostic) => string // default formatDiagnostic
}): DiagnosticReporter<{ method?: 'log' | 'error' | 'warn' }>

Builds a console reporter. createConsoleReporter() uses console.warn and formatDiagnostic; method is overridable per call. When the diagnostic has a cause, it is forwarded to the console method as an additional argument.

Reporters

nostics/reporters/node

import { createFileReporter } from 'nostics/reporters/node'
function createFileReporter(options?: {
  logFile?: string
  excludeStackFrames?: readonly RegExp[]
}): DiagnosticReporter

Appends one JSON line per diagnostic. Default file: .nostics.log. excludeStackFrames defaults to [/\/node_modules\//i]; pass [] to keep every frame.

nostics/reporters/fetch

import { createFetchReporter } from 'nostics/reporters/fetch'
function createFetchReporter(url: string): DiagnosticReporter

POSTs JSON.stringify(diagnostic) to url with Content-Type: application/json. Fetch failures are swallowed.

nostics/reporters/dev

import { createDevReporter } from 'nostics/reporters/dev'

createDevReporter() builds a reporter that sends diagnostic.toJSON() over import.meta.hot.send('nostics:report', payload). Outside Vite, it warns and does nothing else.

Formatters

nostics/formatters/ansi

import { ansiFormatter } from 'nostics/formatters/ansi'
function ansiFormatter(colors: Colors): (diagnostic: Diagnostic) => string
interface Colors {
  red: (s: string) => string
  yellow: (s: string) => string
  cyan: (s: string) => string
  gray: (s: string) => string
  bold: (s: string) => string
  dim: (s: string) => string
}

nostics/formatters/json

import { jsonFormatter } from 'nostics/formatters/json'
const jsonFormatter: (diagnostic: Diagnostic) => string

Calls JSON.stringify(diagnostic).

Plugins

The build-time plugins ship in the separate @nostics/unplugin package:

pnpm add -D @nostics/unplugin

@nostics/unplugin/strip-transform

import { nosticsStrip } from '@nostics/unplugin/strip-transform'

Build-time plugin that marks defineDiagnostics() calls as pure and guards report-only diagnostic expression statements with process.env.NODE_ENV !== "production".

nosticsStrip.vite({
  packageName: 'nostics',
})

Options:

FieldDefaultDescription
packageName'nostics'Package name to detect imports from

@nostics/unplugin/dev-server-collector

import { nosticsCollector } from '@nostics/unplugin/dev-server-collector'

Vite dev-server plugin that listens for nostics:report events and appends diagnostics to a local file.

nosticsCollector.vite({
  logFile: '.nostics.log',
  debug: false,
  excludeStackFrames: [/\/node_modules\//],
})

Options:

FieldDefaultDescription
logFile'.nostics.log'Output file
debug!!process.env.DEBUGLog collector activity
excludeStackFrames[/\/node_modules\//i]Remove matching stack frames before writing. Pass [] to keep every frame

Only the Vite adapter is meaningful for nosticsCollector.

Copyright © 2026