---
title: "Defining diagnostics"
description: "Declare stable codes, typed params, structured data, docs links, sources, and causes."
canonical_url: "https://nostics.dev/guide/defining-diagnostics"
---
# Defining diagnostics

> Declare stable codes, typed params, structured data, docs links, sources, and causes.

Diagnostics work best when you treat them as a catalog. Keep the definitions close together, give each one a **permanent** code, and make the fix specific.

## Shape

```ts
import { createConsoleReporter, defineDiagnostics } from 'nostics'

export 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}".`
      },
      data: (p: { src: string, mode: 'client' | 'server' }) => ({
        src: p.src,
        mode: p.mode,
      }),
    },
  },
})
```

Each key becomes a callable handle:

```ts
diagnostics.NUXT_B2011({
  src: pluginSrc,
  mode: 'client',
})
throw diagnostics.NUXT_B2011({
  src: pluginSrc,
  mode: 'client',
})
```

Calling it creates a fresh `Diagnostic`, runs every reporter, and returns the instance.

## Params

`why`, `fix`, and `data` can use functions. Function params are inferred and required at the call site.

```ts
export const diagnostics = defineDiagnostics({
  codes: {
    NUXT_B5001: {
      why: (p: { value: string, configPath: string }) =>
        `Invalid compatibilityDate "${p.value}" in ${p.configPath}.`,
      fix: (p: { example: string }) => `Use an ISO date like "${p.example}", or "latest".`,
    },
  },
})

// somewhere in config validation
diagnostics.NUXT_B5001({
  configPath: config.filepath,
  value: config.compatibilityDate,
  example: '2024-04-03',
})
```

Params from `why`, `fix`, and `data` are combined. In the example above, `value`, `configPath`, and `example` are required.

## Structured data

Use `data` for machine-readable information that depends on the diagnostic code. It can be a static object or a function of the shared params.

```ts
const diagnostic = defineDiagnostics({
  codes: {
    NUXT_B5001: {
      why: (p: { value: string }) => `Invalid value "${p.value}".`,
      data: (p: { value: string }) => ({
        received: p.value,
        expected: 'ISO date' as const,
      }),
    },
  },
}).NUXT_B5001({ value: 'today' })

diagnostic.data.received // string
diagnostic.data.expected // "ISO date"
```

Each code keeps its own `data` type. `toJSON()` includes the resolved object, so JSON reporters keep it too. Use JSON-compatible values when a reporter serializes the diagnostic.

## Call-site fields

Two fields belong at the place where you report the diagnostic:

```ts
try {
  await loadConfig()
}
catch (cause) {
  throw diagnostics.NUXT_B2011({
    src: pluginSrc,
    mode: 'client',
    cause,
    sources: [
      pluginSrc + ':' + line + ':' + column, // ./path/to/file:10:5
    ],
  })
}
```

`cause` preserves the original error. `sources` points at user code when the JavaScript stack would point inside your library. The `sources` is especially important for build and config diagnostics, where the problem is often in user files but the error is thrown from your library, so the stack trace is not helpful. Reporters can use `cause` and `sources` to give better output.

<warning>

Because they share the params object, `cause` and `sources` are reserved names: a `why`, `fix`, or `data` function cannot take a param with these names. `defineDiagnostics()` gives a type error when one does.

</warning>

## Docs URLs

Use `docsBase` to create the docs URL for each code. A function gives you full control.

```ts
defineDiagnostics({
  docsBase: code => `https://nuxt.com/e/${code.replace('NUXT_', '').toLowerCase()}`,
  codes: {
    NUXT_B2011: { why: 'Plugin mode conflicts with file suffix.' },
  },
})
```

`NUXT_B2011` gets `https://nuxt.com/e/b2011` printed in the diagnostic.

Use a string when your URL structure is regular and the lowercased code can be appended.

```ts
defineDiagnostics({
  docsBase: 'https://nuxt.com/errors',
  codes: {
    NUXT_B2011: { why: 'Plugin mode conflicts with file suffix.' },
  },
})
```

`NUXT_B2011` gets `https://nuxt.com/errors/nuxt_b2011`.

Set `docs` on a code to override the URL, or `false` to omit it.

```ts
defineDiagnostics({
  docsBase: 'https://nuxt.com/e',
  codes: {
    NUXT_B2011: {
      why: 'Plugin mode conflicts with file suffix.',
      docs: 'https://nuxt.com/docs/guide/directory-structure/plugins',
    },
    NUXT_I001: {
      why: 'Using default Nuxt configuration.',
      docs: false,
    },
  },
})
```

## Codes

Pick a format and keep it stable. We recommend a structured shape that scales across many codes:

```txt
<PREFIX>_<CATEGORY><NUMBER>
```

Examples:

```txt
NUXT_B2011
NUXT_R1001
NUXT_D0042
NUXT_C0100
```

Common category letters are `C` for config, `R` for runtime, `B` for build, `D` for deprecation, `W` for warning, and `E` for error. The exact letters matter less than keeping them consistent.

<tip>

Once a code is published, do not rename it or reuse it for a different problem. This is crucial for users to find the right docs and for the production strip plugin to work correctly.

</tip>

This shape is only a convention, not a requirement. A code is any string, so an explicit name like `invalidDate` works just as well and reads clearer when you only have a few:

```ts [src/diagnostics.ts]
export const diagnostics = defineDiagnostics({
  codes: {
    invalidDate: {
      why: (p: { value: string }) => `...`,
      fix: (p: { example: string }) => `...`,
    },
    missingConfig: {
      why: (p: { path: string }) => `...`,
      fix: () => `...`,
    },
  },
})

diagnostics.invalidDate({ value, example })
diagnostics.missingConfig({ path })
```

## Split files

For small libraries, one `src/diagnostics.ts` file is enough. For larger ones, split by area and export the handles directly.

```txt
src/diagnostics/
  build.ts
  config.ts
  runtime.ts
```

```ts [src/diagnostics/config.ts]
export const configDiagnostics = defineDiagnostics({
  docsBase: code => `https://nuxt.com/e/${code.replace('NUXT_', '').toLowerCase()}`,
  codes: {
    NUXT_C001: { why: 'Could not load Nuxt configuration.' },
  },
})
```

Direct exports are easier for the production strip plugin to track than factory wrappers or deep barrels.

## Write good fixes

Good diagnostics say what happened and what to do next.

```ts
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}".`
  },
}
```

Avoid fixes that only restate the problem or are too vague to be helpful.

```ts
NUXT_B2011: {
  why: 'Plugin mode is wrong.',
  fix: 'Fix the plugin.',
}
```


## Sitemap

See the full [sitemap](https://nostics.dev/sitemap.md) for all pages.
