Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ If the server starts without a valid `NUXT_DATABASE_URL`, it stops before servin
- [Coercion of `NUXT_*` strings](https://nuxt-safe-runtime-config.onmax.me/guide/environment-overrides) to the booleans, numbers, enums and JSON values your schema expects, and schema modules for transforms
- [Generated types](https://nuxt-safe-runtime-config.onmax.me/guide/type-safety) for `useSafeRuntimeConfig()` in the app and in `server/`
- [`.env.example` as the schema](https://nuxt-safe-runtime-config.onmax.me/guide/env-schema) (experimental), so builds need no secrets
- An [ESLint rule](https://nuxt-safe-runtime-config.onmax.me/integrations/eslint) that migrates `useRuntimeConfig()` calls
- An [ESLint rule](https://nuxt-safe-runtime-config.onmax.me/guide/eslint) that migrates `useRuntimeConfig()` calls
- A [Nitro module](https://nuxt-safe-runtime-config.onmax.me/guide/nitro) for Nitro apps without Nuxt

Supports Nuxt 4 and the Nuxt 5 nightly, on Nitro 2 and 3.
Expand Down
70 changes: 27 additions & 43 deletions docs/content/1.guide/1.index.md
Original file line number Diff line number Diff line change
@@ -1,66 +1,50 @@
---
title: Introduction
description: What Nuxt Safe Runtime Config checks, and which schema source and validation mode to pick.
description: Fail the build or the server start when runtime config is wrong, and read it through a composable typed from your schema.
navigation.icon: i-ph-book-open
---

`useRuntimeConfig()` returns whatever ends up in runtime config, which is the defaults in `nuxt.config.ts` replaced by any `NUXT_*` environment variable set when the server starts. Nothing checks that `NUXT_DATABASE_URL` is set, that `NUXT_PORT` is a number, or that `NUXT_PUBLIC_REPLAY_ENABLED=false` arrives as `false` instead of the string `'false'`. The types come from the defaults, so a secret that defaults to `''` is typed `string` even when production never sets it.
Nuxt never checks runtime config. A server that starts without `NUXT_DATABASE_URL` boots fine, and the first request that needs the database fails. On Nitro 3, `NUXT_PUBLIC_REPLAY_ENABLED=false` reaches your code as the string `'false'`, which is truthy. And `useRuntimeConfig()` takes its types from the defaults in `nuxt.config.ts`, so a secret that defaults to `''` is typed `string` whether anyone set it or not.

This module puts a schema on runtime config. It validates the values when you build or when the server starts, and `useSafeRuntimeConfig()` returns them typed from that schema.
This module puts a schema on runtime config. When a value is missing or has the wrong type, `nuxt build` stops:

```txt
$ nuxt build
[safe-runtime-config] Validation failed!
1. databaseUrl: Invalid key: Expected "databaseUrl" but received undefined
2. public.apiBase: Invalid URL: Received "not a url"
```

When the values pass, `useSafeRuntimeConfig()` returns them with the types your schema declares:

```ts [server/api/report.post.ts]
export default defineEventHandler((event) => {
const config = useSafeRuntimeConfig(event)
config.databaseUrl // string
config.public.replayEnabled // boolean, also when the server starts with NUXT_PUBLIC_REPLAY_ENABLED=false
config.public.replayEnabled // boolean, even when the server starts with NUXT_PUBLIC_REPLAY_ENABLED=false
})
```

## Choose a schema source

Each app uses one of the two.
The schema can be a [Valibot, Zod or ArkType](/guide/installation) object, or an annotated [`.env.example`](/guide/env-schema).

::card-group
:::card
---
icon: i-ph-brackets-curly
title: Standard Schema
to: /guide/installation
---
Set `$schema` to a Valibot, Zod or ArkType schema. Use it when you already use one of these libraries, or need transforms, unions or cross-field rules.
:::
## What it checks

:::card
---
icon: i-ph-file-text
title: .env.example (experimental)
to: /guide/env-schema
---
Set `envSchema` to a committed `.env.example` with `@type` annotations. Use it when every value comes from the deployment environment and builds must run without secrets.
:::
::

## Choose when to validate
- The values in `nuxt.config.ts` during `nuxt dev` and `nuxt build`, or the values the server starts with after `NUXT_*` overrides. [Validation](/guide/validation) explains which one you want.
- `NUXT_*` strings, which it converts to the booleans, numbers, enums and JSON your schema asks for before checking them. See [Environment variables](/guide/environment-overrides).
- Your code, through types generated from the schema for the app and for `server/`. See [Types](/guide/type-safety).

| You deploy | Validate | Option |
| --- | --- | --- |
| The values written in `nuxt.config.ts`, unchanged | at build | default |
| Values injected as `NUXT_*` variables when the server starts | at runtime | `validateAtRuntime: true` |
| Real values at build time and possibly different ones at runtime | both | `validateAtBuild: true` and `validateAtRuntime: true` |
## What it costs

[Validation](/guide/validation) explains each mode and what a failure does.
You keep a schema next to `runtimeConfig`, and every new key goes in both. The `.env.example` source avoids that, because the file declares the keys.

## What the module adds
To check values at server start, the module converts an inline schema to JSON Schema at build time. Transforms and custom refinements have no JSON Schema form, so a schema that uses them moves to its own file.

- `useSafeRuntimeConfig()` and `useSafeRuntimeConfig(event)`, auto-imported in the app and in `server/`
- generated types in `.nuxt/types/safe-runtime-config.d.ts`
- an [ESLint rule](/integrations/eslint) that flags untyped `useRuntimeConfig()` calls
- a [Nitro module](/guide/nitro) for Nitro apps without Nuxt
## Requirements

## Compatibility
Nuxt 4, or the Nuxt 5 nightly. It runs on Nitro 2 (`nitropack` 2.13 or later) and Nitro 3. The `.env.example` source needs Node.js 22 or later for `nuxt prepare` and `nuxt build`.

Nuxt 4 is supported. CI also runs Nuxt 4.2+ with `future.compatibilityVersion: 5` and the Nuxt 5 nightly channel (`nuxt-nightly@5x`). Validation runs on Nitro 2 (`nitropack` 2.13+) and Nitro 3.

On Nuxt 5, prefer [ViteHub Env](/guide/migrate-to-vitehub-env). The module still works there, and one command migrates an app.
::tip
On Nuxt 5, use [ViteHub Env](https://vitehub.dev/docs/env) instead. It reads the same `.env.example`, keeps secrets redacted until you unseal them, and one command [migrates an app](/guide/migrate-to-vitehub-env).
::

The `.env.example` source needs Node.js 22 or later during `nuxt prepare` and `nuxt build`.
[Install the module](/guide/installation) to add a schema to an existing app.
98 changes: 74 additions & 24 deletions docs/content/1.guide/2.installation.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Installation
description: Add a schema to your runtime config, read it with useSafeRuntimeConfig(), and see a validation failure.
description: Add the module, write a schema for your runtime config in Valibot, Zod or ArkType, and watch the build reject a bad value.
navigation.icon: i-ph-download-simple
---

Expand All @@ -11,16 +11,14 @@ Add nuxt-safe-runtime-config to my Nuxt app.

- Read https://nuxt-safe-runtime-config.onmax.me/raw/guide/installation.md first
- Run `npx nuxi module add nuxt-safe-runtime-config`
- Write a Standard Schema (Valibot, Zod or ArkType, whichever the app already uses) that covers every key in `runtimeConfig`, and set it as `safeRuntimeConfig.$schema`
- If values come from `NUXT_*` variables at deploy time, also set `validateAtRuntime: true`
- Replace `useRuntimeConfig()` with `useSafeRuntimeConfig()`; pass `event` in server handlers
- Run `nuxi prepare` and the typecheck, then fix every reported config error instead of casting
- Write a schema for every key in `runtimeConfig`, with the schema library the app already uses (Valibot, Zod or ArkType), and set it as `safeRuntimeConfig.$schema`
- If production sets values through `NUXT_*` variables, also set `validateAtRuntime: true`
- Replace `useRuntimeConfig()` with `useSafeRuntimeConfig()`, passing `event` in server handlers
- Run `nuxi prepare` and the typecheck, and fix each config error instead of casting
```

::

This page takes you from install to a typed config and a failing check. It uses Valibot; the [schema pages](/schemas) show the same schema in Zod and ArkType.

::steps

### Install the module
Expand All @@ -29,17 +27,19 @@ This page takes you from install to a typed config and a failing check. It uses
npx nuxi module add nuxt-safe-runtime-config
```

Install your schema library too if the app does not have one yet:
Add a schema library if the app has none. The examples use Valibot, and each block has a Zod and an ArkType tab.

```bash
pnpm add valibot
```

### Add the schema
### Describe your runtime config

Describe every key you keep in `runtimeConfig`, including `public`:
Write a schema that covers every key in `runtimeConfig`, `public` included, and pass it as `$schema`:

```ts [nuxt.config.ts]
::code-group

```ts [Valibot]
import * as v from 'valibot'

export default defineNuxtConfig({
Expand All @@ -48,31 +48,85 @@ export default defineNuxtConfig({
databaseUrl: 'postgresql://localhost:5432/app',
public: {
apiBase: 'https://api.example.com',
replayEnabled: false,
},
},
safeRuntimeConfig: {
$schema: v.object({
databaseUrl: v.pipe(v.string(), v.url()),
public: v.object({
apiBase: v.pipe(v.string(), v.url()),
replayEnabled: v.boolean(),
}),
}),
},
})
```

```ts [Zod]
import { z } from 'zod'

export default defineNuxtConfig({
modules: ['nuxt-safe-runtime-config'],
runtimeConfig: {
databaseUrl: 'postgresql://localhost:5432/app',
public: {
apiBase: 'https://api.example.com',
replayEnabled: false,
},
},
safeRuntimeConfig: {
$schema: z.object({
databaseUrl: z.string().url(),
public: z.object({
apiBase: z.string().url(),
replayEnabled: z.boolean(),
}),
}),
},
})
```

```ts [ArkType]
import { type } from 'arktype'

export default defineNuxtConfig({
modules: ['nuxt-safe-runtime-config'],
runtimeConfig: {
databaseUrl: 'postgresql://localhost:5432/app',
public: {
apiBase: 'https://api.example.com',
replayEnabled: false,
},
},
safeRuntimeConfig: {
$schema: type({
databaseUrl: 'string.url',
public: {
apiBase: 'string.url',
replayEnabled: 'boolean',
},
}),
},
})
```

::

Any library that implements [Standard Schema](https://standardschema.dev/) works. Valibot 1, Zod 3.24 and later, and ArkType 2 do.

### Read the config

`useSafeRuntimeConfig()` is auto-imported in components, plugins and `server/`:

```vue [app.vue]
<script setup lang="ts">
const config = useSafeRuntimeConfig()
// config.public.apiBase: string
config.public.apiBase // string
</script>
```

In server handlers, pass the event, as you would to `useRuntimeConfig(event)`:
In a server handler, pass the event, as you would to `useRuntimeConfig(event)`:

```ts [server/api/health.get.ts]
export default defineEventHandler((event) => {
Expand All @@ -83,20 +137,20 @@ export default defineEventHandler((event) => {

### Break it on purpose

Change `apiBase` to `'not a url'` and run `nuxt dev`. Startup stops with:
Set `apiBase` to `'not a url'` and run `nuxt dev`. It stops before serving anything:

```txt
[safe-runtime-config] Validation failed!
1. public.apiBase: Invalid URL: Received "not a url"
```

The wording of each issue comes from your schema library.
Each message comes from your schema library, so Zod and ArkType word it differently.

::

## Deploying with environment variables
## If production sets `NUXT_*` variables

The check above runs against `nuxt.config.ts`. If production sets `NUXT_DATABASE_URL` or `NUXT_PUBLIC_API_BASE` when the server starts, the build never sees those values. Turn on runtime validation:
The check above reads `nuxt.config.ts`. When production sets `NUXT_DATABASE_URL` as the server starts, the build never sees that value. Add `validateAtRuntime: true` and the server checks what it actually received:

```ts [nuxt.config.ts]
export default defineNuxtConfig({
Expand All @@ -107,18 +161,14 @@ export default defineNuxtConfig({
})
```

The server then validates the values it starts with, and the build stops checking the placeholders in `nuxt.config.ts`. [Validation](/guide/validation) covers the trade-off.
[Validation](/guide/validation) explains when to check at build, at start, or both.

::tip
If your editor type-checks a file outside Nuxt's auto-imports, import the composable from `#imports`:
A file outside Nuxt's auto-imports, such as a shared helper that your editor type-checks on its own, can import the composable from `#imports`:

```ts
import { useSafeRuntimeConfig } from '#imports'
```
::

## Next steps

- [Validation](/guide/validation): build or runtime, and what a failure does
- [Environment overrides](/guide/environment-overrides): how `NUXT_*` strings become booleans, numbers and parsed values
- [ESLint](/integrations/eslint): find the remaining `useRuntimeConfig()` calls
Next, run the [ESLint rule](/guide/eslint) to find the `useRuntimeConfig()` calls that are still untyped.
Loading
Loading