diff --git a/README.md b/README.md
index d045a00..d9897a4 100644
--- a/README.md
+++ b/README.md
@@ -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.
diff --git a/docs/content/1.guide/1.index.md b/docs/content/1.guide/1.index.md
index 145e612..7576ec9 100644
--- a/docs/content/1.guide/1.index.md
+++ b/docs/content/1.guide/1.index.md
@@ -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.
diff --git a/docs/content/1.guide/2.installation.md b/docs/content/1.guide/2.installation.md
index b1c37ea..abd7e5a 100644
--- a/docs/content/1.guide/2.installation.md
+++ b/docs/content/1.guide/2.installation.md
@@ -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
---
@@ -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
@@ -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({
@@ -48,6 +48,7 @@ export default defineNuxtConfig({
databaseUrl: 'postgresql://localhost:5432/app',
public: {
apiBase: 'https://api.example.com',
+ replayEnabled: false,
},
},
safeRuntimeConfig: {
@@ -55,12 +56,65 @@ export default defineNuxtConfig({
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/`:
@@ -68,11 +122,11 @@ export default defineNuxtConfig({
```vue [app.vue]
```
-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) => {
@@ -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({
@@ -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.
diff --git a/docs/content/1.guide/3.validation.md b/docs/content/1.guide/3.validation.md
index 1b40549..4e2efd5 100644
--- a/docs/content/1.guide/3.validation.md
+++ b/docs/content/1.guide/3.validation.md
@@ -1,14 +1,20 @@
---
title: Validation
-description: Validate runtime config at build, at server start, or both, and control what a failure does.
+description: Check runtime config at build, at server start, or both, depending on where your deployed values come from, and choose what a failure does.
navigation.icon: i-ph-seal-check
---
-Runtime config has two moments where it can be wrong. At build time it holds what `nuxt.config.ts` says. When the server starts, Nitro replaces those values with any matching `NUXT_*` environment variables. Validate at the moment whose values you actually deploy.
+Runtime config holds different values at two moments. During the build it holds what `nuxt.config.ts` says. When the built server starts, Nitro replaces each value that has a matching `NUXT_*` environment variable. Check the moment whose values you deploy.
-## Build validation
+| Where production values come from | Check at | Options |
+| --- | --- | --- |
+| `nuxt.config.ts`, including values CI reads from `process.env` while building | build | none, this is the default |
+| `NUXT_*` variables set when the server starts | server start | `validateAtRuntime: true` |
+| Both: real values at build, and overrides at start | both | `validateAtBuild: true`, `validateAtRuntime: true` |
+
+## At build
-Build validation is the default. It runs your schema against the resolved `nuxt.config.ts` values during `nuxt dev` and `nuxt build`, before anything ships.
+With only `$schema` set, the module runs your schema against the resolved `nuxt.config.ts` values during `nuxt dev` and `nuxt build`:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@@ -18,13 +24,11 @@ export default defineNuxtConfig({
})
```
-Use it when the values in `nuxt.config.ts` are the values you deploy, for example when CI reads secrets from the environment while building. Nothing about validation runs in production.
-
-It cannot see variables that are only set when the server starts. A build that passes with `databaseUrl: ''` replaced later by `NUXT_DATABASE_URL` tells you nothing about that variable.
+The module adds no plugin or middleware to the server, and nothing is checked in production.
-## Runtime validation
+A build check can't see a variable that only exists on the server. If CI builds with `databaseUrl: ''` and production sets `NUXT_DATABASE_URL`, the build check either fails on the empty placeholder or passes on a value production never uses.
-Runtime validation checks the config the server actually starts with, after Nitro applies `NUXT_*` overrides.
+## At server start
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@@ -35,20 +39,20 @@ export default defineNuxtConfig({
})
```
-With runtime validation on:
+The module adds a Nitro plugin and a middleware. When the server starts:
-1. A Nitro plugin validates `useRuntimeConfig()` on cold start, before your own server plugins.
-2. Overrides are [coerced](/guide/environment-overrides) to the types the schema expects, so `NUXT_PORT=3000` becomes `3000`.
-3. A middleware prepares each request's config before handlers run, so `useSafeRuntimeConfig(event)` returns validated values.
-4. Validated values are written back into runtime config, so Nuxt serializes them into the client payload.
+1. The plugin reads `useRuntimeConfig()` after Nitro has applied `NUXT_*` overrides, before your own server plugins run.
+2. It [converts the strings](/guide/environment-overrides) to the types the schema expects, so `NUXT_PORT=3000` becomes `3000`.
+3. It validates the result and writes the validated values back into runtime config. Nuxt then serializes them into the client payload.
+4. For each request, the middleware prepares the event's config before your handlers run, so `useSafeRuntimeConfig(event)` returns checked values.
-Build validation turns off by default when runtime validation is on, because build-time values are placeholders the environment replaces. The build no longer needs real secrets.
+Turning on runtime validation turns build validation off, because the build values are placeholders that the environment replaces. The build no longer needs real secrets.
-An inline `$schema` is converted to JSON Schema at build time and validated with [@cfworker/json-schema](https://github.com/cfworker/cfworker/tree/main/packages/json-schema), which also runs on edge runtimes. Your schema library is not bundled. A schema with transforms has no JSON Schema form; [put it in a schema module](/guide/environment-overrides#transform-values-with-a-schema-module) and the server runs it as written.
+Your schema library is not bundled into the server. At build time the module converts an inline `$schema` to JSON Schema, and the server checks it with [@cfworker/json-schema](https://github.com/cfworker/cfworker/tree/main/packages/json-schema), which also runs on edge runtimes. A schema with transforms has no JSON Schema form. [Move it to its own file](/guide/environment-overrides#transform-values-with-a-schema-module) and the server runs it as written.
-## Both
+## At both
-Turn build validation back on when the build has real values and you also want to catch what the deployment changes:
+Turn build validation back on when the build has real values and the deployment may still override some of them:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@@ -60,30 +64,30 @@ export default defineNuxtConfig({
})
```
-## When validation fails
+## When a check fails
-`onError` decides what a failure does, at build and at runtime:
+`onError` decides what a failure does:
-| `onError` | At build | At runtime |
+| `onError` | At build | At server start |
| --- | --- | --- |
-| `'throw'` (default) | Logs the issues and stops `nuxt dev` or `nuxt build` | Stops the server for a synchronous schema; rejects requests for an asynchronous schema or an invalid event config |
+| `'throw'` (default) | Logs the issues and stops `nuxt dev` or `nuxt build` | Stops the server with a synchronous schema. With an asynchronous schema, or when a request's own config fails, the request fails instead |
| `'warn'` | Logs the issues and continues | Logs the issues and continues |
-| `'ignore'` | Continues silently | Continues silently |
+| `'ignore'` | Continues without logging | Continues without logging |
-Keep `'throw'` in CI and production. `'warn'` is for migrating an app whose config does not pass yet.
+Keep `'throw'` in CI and production. Use `'warn'` while you migrate an app whose config does not pass yet.
-Build validation runs your schema library and lists each issue with its path:
+The build check runs your schema library and prints one line per issue:
```txt
[safe-runtime-config] Validation failed!
- 1. databaseUrl: Invalid type: Expected string but received undefined
- 2. public.apiBase: Invalid URL: Received "localhost"
+ 1. databaseUrl: Invalid key: Expected "databaseUrl" but received undefined
+ 2. public.apiBase: Invalid URL: Received "not a url"
```
-Runtime validation of an inline schema reports JSON Schema errors with their JSON Pointer:
+The server check of an inline schema prints JSON Schema errors, each with a JSON Pointer to the value:
```txt
[safe-runtime-config] Runtime validation failed: #: Property "databaseUrl" does not match schema., #/databaseUrl: String does not match format "uri".
```
-A schema module reports in the first format, since the server runs your library.
+A schema module prints in the first format at server start too, because the server runs your library.
diff --git a/docs/content/1.guide/4.environment-overrides.md b/docs/content/1.guide/4.environment-overrides.md
index 912a9b1..6849cde 100644
--- a/docs/content/1.guide/4.environment-overrides.md
+++ b/docs/content/1.guide/4.environment-overrides.md
@@ -1,27 +1,27 @@
---
-title: Environment overrides
-description: How NUXT_* strings become the booleans, numbers and objects your schema expects, and how to transform values beyond that.
+title: Environment variables
+description: How NUXT_* strings become the booleans, numbers and JSON your schema expects, and where transforms and refinements go.
navigation.icon: i-ph-arrows-left-right
---
-Environment variables are strings. Nitro 3 passes them into runtime config unchanged. Nitro 2 parses some of them, so `NUXT_FLAG=1` arrives as the number `1` and `NUXT_LABEL=123` as `123`. Either way, a schema that says `boolean()` would reject `NUXT_PUBLIC_REPLAY_ENABLED=false`.
+Environment variables are strings, and Nitro hands them to runtime config in two different ways. Nitro 3 passes them unchanged, so `NUXT_PUBLIC_REPLAY_ENABLED=false` arrives as `'false'`. Nitro 2 parses some of them, so `NUXT_PORT=3000` arrives as the number `3000` and `NUXT_VERSION=1.10` as `1.1`. A schema that says `boolean()` rejects the first, and one that says `string()` rejects the others.
-Everything on this page applies with `validateAtRuntime: true`.
+With `validateAtRuntime: true`, the module converts these values before it validates them. Everything on this page needs that option.
## Coercion
-Before validating, the module converts each value the schema would reject into the type it expects:
+The module converts a value only when the schema would reject it as it is:
-| Schema expects | Converted values |
+| The schema expects | The module converts |
| --- | --- |
-| `boolean` | `'true'`, `'false'`, `'1'`, `'0'` in any case, and `1`, `0` |
-| `number` | numeric strings such as `'0.5'` or `'3000'` |
-| `integer` | integral strings such as `'3000'` |
+| `boolean` | `'true'`, `'false'`, `'1'` and `'0'` in any case, and the numbers `1` and `0` |
+| `number` | numeric strings, such as `'0.5'` or `'3000'` |
+| `integer` | integral strings, such as `'3000'` |
| `string` | integers and booleans that Nitro 2 parsed, such as `123` or `true` |
-| array or object | JSON strings such as `'["email","github"]'` |
-| enum or literal | strings that convert to one of the allowed values |
+| an array or an object | JSON strings, such as `'["email","github"]'` |
+| an enum or a literal | strings that convert to one of the allowed values |
-A plain schema is then enough:
+So a plain schema is enough:
```ts [nuxt.config.ts]
import * as v from 'valibot'
@@ -42,20 +42,32 @@ export default defineNuxtConfig({
})
```
-Start the server with `NUXT_PUBLIC_REPLAY_ENABLED=true NUXT_PUBLIC_SAMPLE_RATE=0.4`, and `useSafeRuntimeConfig().public` is `{ replayEnabled: true, sampleRate: 0.4 }` on the server and in the client payload.
+Start the server with `NUXT_PUBLIC_REPLAY_ENABLED=true NUXT_PUBLIC_SAMPLE_RATE=0.4` and `useSafeRuntimeConfig().public` is `{ replayEnabled: true, sampleRate: 0.4 }`, on the server and in the client payload.
-The rules are conservative:
+Don't reach for `z.coerce` or a `v.transform()` to do this yourself. `z.coerce.boolean()` turns `'false'` into `true`.
-- A value the schema already accepts is left alone. A field typed `union([boolean(), string()])` keeps `'true'` as a string.
-- A value that cannot be converted still fails. `NUXT_PUBLIC_REPLAY_ENABLED=maybe` is an error, not `false`.
-- Nitro 2 turns `NUXT_VERSION=1.10` into the number `1.1`. The original spelling is gone, so a `string` field rejects it rather than guessing `'1.1'`.
+Coercion never guesses:
+
+- A value the schema already accepts stays as it is. A field typed `union([boolean(), string()])` keeps `'true'` as a string.
+- A value it cannot convert still fails. `NUXT_PUBLIC_REPLAY_ENABLED=maybe` is an error, not `false`.
+- Nitro 2 has already turned `NUXT_VERSION=1.10` into `1.1` and the original spelling is gone, so a `string` field rejects it instead of returning `'1.1'`.
- In a union of objects, a branch whose literal fields contradict the value, such as `kind: 'a'`, is skipped.
-The module writes the converted values back into the per-request config on Nitro 2 and the shared config on Nitro 3. Code that still calls `useRuntimeConfig(event)` sees them too.
+The module writes the converted values back into runtime config, so code that still calls `useRuntimeConfig(event)` sees them too.
## Transform values with a schema module
-Coercion only fixes types. To parse, normalize or derive values, move the schema into its own file and default-export it:
+Coercion fixes types. To split a list, trim a trailing slash or check one field against another, the server has to run your schema library, and an inline `$schema` can't do that. The module converts it to JSON Schema at build time, and some features don't survive:
+
+| Library | Fails the build | Converts, but the server skips the check |
+| --- | --- | --- |
+| Valibot | `v.transform()`, `v.check()` | |
+| Zod | `.transform()` | `.refine()`, `.superRefine()` |
+| ArkType | | `.narrow()`, morphs such as `.pipe()` |
+
+The right column matters most. A `.refine()` passes the build check, because the build runs Zod as written, and then the server never runs it.
+
+Put the schema in its own file and default-export it:
```ts [runtime-config.schema.ts]
import * as v from 'valibot'
@@ -71,7 +83,7 @@ export default v.object({
})
```
-Point `$schema` at the file, relative to the project root:
+Then point `$schema` at the file, relative to the project root:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@@ -82,9 +94,9 @@ export default defineNuxtConfig({
})
```
-The server runs the original schema once after Nitro applies overrides, and `useSafeRuntimeConfig()` returns its output, so `allowedOrigins` is a `string[]`. Transformed `public` values reach the client payload. The [generated types](/guide/type-safety) switch to the schema's output type.
+The server runs the schema once, after Nitro applies overrides, and `useSafeRuntimeConfig()` returns its output. `allowedOrigins` is a `string[]`, transformed `public` values reach the client payload, and the [generated types](/guide/type-safety) describe the output.
-The module still derives a JSON Schema for coercion when it can. Schemas with transforms usually have none, so they receive the raw values, including Nitro 2's parsed numbers and booleans, and must accept both:
+A schema with transforms usually has no JSON Schema form, so the module can't coerce its input. It receives the raw values, which on Nitro 2 includes parsed numbers and booleans. Accept both, and parse in the schema so the code that reads the config doesn't have to:
```ts [runtime-config.schema.ts]
const runtimeBoolean = v.pipe(
@@ -93,15 +105,11 @@ const runtimeBoolean = v.pipe(
)
```
-Keep parsing in the schema. Code that reads the config should not repeat `value === true || value === 'true'`.
-
-### Asynchronous schemas
-
-Asynchronous schemas work. Request handlers and Nuxt rendering wait for the result. Nitro runs startup plugins synchronously, so a server plugin that reads `useSafeRuntimeConfig()` during initialization needs a synchronous schema.
+An asynchronous schema works too. Request handlers and Nuxt rendering wait for its result. Nitro runs server plugins synchronously, though, so a plugin that reads `useSafeRuntimeConfig()` while it initializes needs a synchronous schema.
-## Request-scoped config
+## Config per request
-On Nitro 2, `useRuntimeConfig(event)` is a per-request copy. Platforms such as Cloudflare Workers resolve environment variables per request. `useSafeRuntimeConfig(event)` is its validated counterpart:
+On Nitro 2, `useRuntimeConfig(event)` returns a copy of the config for that request, and platforms such as Cloudflare Workers fill it from that request's environment. `useSafeRuntimeConfig(event)` returns the checked version:
```ts [server/utils/cube-token.ts]
import type { H3Event } from 'h3'
@@ -112,4 +120,4 @@ export function createCubeToken(event: H3Event): string {
}
```
-When a request has the same values as startup, as it always does on a Node server, it gets a copy of the startup result and the schema does not run again. Otherwise its config is coerced and validated once per request. On Nitro 3, which has one process-wide config, `useSafeRuntimeConfig(event)` returns the same object as `useSafeRuntimeConfig()`.
+On a Node server every request has the startup values, so each one gets a copy of the startup result and the schema doesn't run again. When a request's values differ, its config is converted and validated once for that request. Nitro 3 has one config for the whole process, so there `useSafeRuntimeConfig(event)` returns the same object as `useSafeRuntimeConfig()`.
diff --git a/docs/content/1.guide/5.env-schema.md b/docs/content/1.guide/5.env-schema.md
deleted file mode 100644
index d0ad1a3..0000000
--- a/docs/content/1.guide/5.env-schema.md
+++ /dev/null
@@ -1,133 +0,0 @@
----
-title: .env.example schemas
-description: Declare runtime config in a committed .env.example, build without deployment values, and validate injected NUXT_* variables when the server starts.
-navigation.icon: i-ph-file-text
-navigation.badge: Experimental
----
-
-::warning
-This schema source is experimental. Its syntax and behavior can change in a minor release.
-::
-
-Most apps already keep a `.env.example` listing every variable. With `envSchema`, that file becomes the schema. Each entry declares a runtime config key, its type, whether it is required, and whether the browser may see it. No `runtimeConfig` block and no schema library are needed.
-
-Use it when every value comes from the deployment environment and the build must not need secrets. Use [`$schema`](/guide/installation) instead for transforms, custom types, optional nested properties, cross-field rules or computed defaults. An app uses one source, not both.
-
-::steps
-
-### Annotate the file
-
-```dotenv [.env.example]
-# Database connection injected when the server starts.
-# @type=url @example="postgresql://example.test/database"
-NUXT_DATABASE_URL=
-
-# @type=string(minLength=16)
-NUXT_API_SECRET=
-
-# @public @type=boolean
-NUXT_PUBLIC_REPLAY_ENABLED=false
-
-# @public @type=number(min=0, max=1)
-NUXT_PUBLIC_SAMPLE_RATE=0.1
-
-# @public @type=enum(debug, info, warn, error)
-NUXT_PUBLIC_LOG_LEVEL=info
-
-# @optional @type=number
-NUXT_REQUEST_LIMIT=
-```
-
-Everything is required and private unless marked otherwise. An assignment such as `=false` is a real default. `KEY=` declares no default. `@example` is documentation only.
-
-### Point the module at it
-
-```ts [nuxt.config.ts]
-export default defineNuxtConfig({
- modules: ['nuxt-safe-runtime-config'],
- safeRuntimeConfig: {
- envSchema: '.env.example',
- },
-})
-```
-
-### Read typed values
-
-```ts
-const config = useSafeRuntimeConfig()
-config.databaseUrl // string
-config.public.replayEnabled // boolean
-config.public.sampleRate // number
-config.public.logLevel // 'debug' | 'info' | 'warn' | 'error'
-config.requestLimit // number | undefined
-```
-
-Types come from the declarations during `nuxt prepare`. Local `.env` values are never read for types.
-
-::
-
-::caution
-Review an existing `.env.example` before enabling this. A placeholder written as `NUXT_API_SECRET=changeme` becomes a real default that ships in the build. Move placeholders to `@example`.
-::
-
-`envSchema` always validates at runtime and skips build validation. Setting `validateAtRuntime: false` is an error. Keep `onError` at `'throw'` so an invalid deployment fails to start.
-
-The [env-spec profile](/schemas/env-spec) defines every decorator, type and default rule.
-
-## Deploy one build with different values
-
-Build with the schema file present and no deployment variables. Start the built server with canonical `NUXT_*` variables:
-
-```bash
-NUXT_DATABASE_URL=postgresql://db.internal/app \
-NUXT_API_SECRET=a-long-production-secret \
-NUXT_PUBLIC_REPLAY_ENABLED=true \
-node .output/server/index.mjs
-```
-
-The same artifact can start again with other credentials and public settings, no rebuild.
-
-The schema owns the config paths it declares. Values set in `runtimeConfig` or inherited from the build environment at those paths do not become defaults, so a credential present in CI never ends up in the artifact. Assignment defaults are bundled, so keep credentials blank in the file.
-
-## Public and private keys
-
-A key reaches the browser only if it starts with `NUXT_PUBLIC_` and is marked `@public` (or `@sensitive=false`). A `NUXT_` key marked `@public` stays private, because the annotation cannot override Nuxt's prefix rule.
-
-## Nested config
-
-Keys map to flat camelCase fields, so `NUXT_DATABASE_URL` becomes `databaseUrl`. To keep an existing nested shape, map keys to paths:
-
-```ts [nuxt.config.ts]
-export default defineNuxtConfig({
- safeRuntimeConfig: {
- envSchema: {
- file: '.env.example',
- paths: {
- NUXT_PUBLIC_POSTHOG_REPLAY_SAMPLE_RATE: 'public.posthog.replaySampleRate',
- },
- },
- },
-})
-```
-
-Each path must convert back to exactly its declared key, the way Nuxt maps `NUXT_*` variables. Reserved keys, duplicate paths, a path that is both a value and an object, and paths that change visibility fail with the file and line.
-
-Editing the schema file in development restarts Nuxt.
-
-## Arrays and objects
-
-Declare JSON values with item and property types, and quote JSON defaults:
-
-```dotenv [.env.example]
-# @type=array(enum(read, write))
-NUXT_ROLES='["read"]'
-
-# @type=object(enabled=boolean, retries=number(min=0), tags=array(string))
-NUXT_SETTINGS='{"enabled":false,"retries":3,"tags":[]}'
-```
-
-`config.roles` is `('read' | 'write')[]`. `config.settings` requires exactly `enabled`, `retries` and `tags`. Bare `array` and `object` accept any JSON array or object. The module validates JSON members as written, so `"false"` inside JSON stays a string and fails a `boolean` property.
-
-## How values are converted
-
-String inputs keep their exact spelling. `NUXT_ACCOUNT_PIN=00123` declared as a string is `'00123'` after startup, although Nitro 2 alone would parse it as `123`. On platforms that build each request's config themselves, a spelling the platform already parsed away cannot be recovered. A value that is present but invalid fails validation; it never falls back to the default. `process.env` keeps its usual `string | undefined` types, and `useRuntimeConfig()` keeps the types Nuxt infers from defaults. Only `useSafeRuntimeConfig()` has the declared types.
diff --git a/docs/content/1.guide/5.type-safety.md b/docs/content/1.guide/5.type-safety.md
new file mode 100644
index 0000000..510a751
--- /dev/null
+++ b/docs/content/1.guide/5.type-safety.md
@@ -0,0 +1,68 @@
+---
+title: Types
+description: useSafeRuntimeConfig() is typed from your schema instead of your defaults. See where the types come from and when to regenerate them.
+navigation.icon: i-ph-shield-check
+---
+
+`useRuntimeConfig()` infers its types from the defaults in `nuxt.config.ts`, which is wrong in three common cases:
+
+```ts [nuxt.config.ts]
+export default defineNuxtConfig({
+ runtimeConfig: {
+ apiSecret: '', // typed string, even when production never sets it
+ sampleRate: 0, // typed number, but on Nitro 3 NUXT_SAMPLE_RATE=0.5 arrives as '0.5'
+ // sentryDsn has no default, so it doesn't exist in the types at all
+ },
+})
+```
+
+`useSafeRuntimeConfig()` takes its types from the schema instead. You don't pass a generic, in components, plugins, `server/api` or `server/utils`:
+
+```ts
+const config = useSafeRuntimeConfig()
+config.public.apiBase // string
+config.port // number | undefined, from optional(number())
+config.missingKey // type error
+```
+
+## Where the types come from
+
+During `nuxt prepare` and `nuxt dev`, the module writes `.nuxt/types/safe-runtime-config.d.ts` and adds it to the app and server TypeScript projects. For the schema on the [Installation](/guide/installation) page it contains:
+
+```ts [.nuxt/types/safe-runtime-config.d.ts]
+export type SafeRuntimeConfig = {
+ databaseUrl: string
+ public: {
+ apiBase: string
+ replayEnabled: boolean
+ }
+}
+```
+
+How it builds that type depends on the schema source:
+
+| Schema source | Type |
+| --- | --- |
+| Inline `$schema` | Converted to JSON Schema, then to TypeScript |
+| A schema module, `$schema: './file'` | The schema's input type, or its output type with `validateAtRuntime: true` |
+| `envSchema` | Each entry's `@type`, whether it's required, and whether it's public |
+
+A schema module switches types because its transforms only run at server start. Without runtime validation, `NUXT_ALLOWED_ORIGINS=a.com,b.com` reaches your code as the string the schema accepts, not the array it would produce.
+
+After you change the schema, run `nuxi prepare` or restart `nuxt dev`. Don't edit the generated file.
+
+## When the types lie
+
+The types describe a config that passed validation. Two cases break that:
+
+- With `onError: 'warn'` or `'ignore'`, a failed check still returns the raw config, untransformed, under the output type. Keep the default `'throw'` wherever you rely on the types.
+- In the browser, Nuxt only ships `public`. Private keys are in the type and `undefined` at runtime, so read them in `server/`:
+
+```ts [server/utils/mailer.ts]
+export function createMailer() {
+ const { smtp } = useSafeRuntimeConfig()
+ return createTransport(smtp)
+}
+```
+
+`useRuntimeConfig()` keeps the types Nuxt gives it. The [ESLint rule](/guide/eslint) finds the calls to move.
diff --git a/docs/content/1.guide/6.env-schema.md b/docs/content/1.guide/6.env-schema.md
new file mode 100644
index 0000000..7980af1
--- /dev/null
+++ b/docs/content/1.guide/6.env-schema.md
@@ -0,0 +1,137 @@
+---
+title: .env.example as schema
+description: Declare runtime config in an annotated .env.example, build without secrets, and check the NUXT_* variables when the server starts.
+navigation.icon: i-ph-file-text
+navigation.badge: Experimental
+---
+
+::warning
+This schema source is experimental. Its syntax and behavior can change in a minor release.
+::
+
+Most apps already commit a `.env.example` that lists every variable. With `envSchema`, that file is the schema. Add a type to each entry and you no longer need a `runtimeConfig` block or a schema library.
+
+Use it when every value comes from the deployment and the build must run without secrets. Stay with [`$schema`](/guide/installation) for transforms, unions, cross-field rules or computed defaults. An app uses one source, not both.
+
+::steps
+
+### Annotate the file
+
+```dotenv [.env.example]
+# Database connection injected when the server starts.
+# @type=url @example="postgresql://example.test/database"
+NUXT_DATABASE_URL=
+
+# @type=string(minLength=16)
+NUXT_API_SECRET=
+
+# @public @type=boolean
+NUXT_PUBLIC_REPLAY_ENABLED=false
+
+# @public @type=number(min=0, max=1)
+NUXT_PUBLIC_SAMPLE_RATE=0.1
+
+# @public @type=enum(debug, info, warn, error)
+NUXT_PUBLIC_LOG_LEVEL=info
+
+# @optional @type=number
+NUXT_REQUEST_LIMIT=
+```
+
+Every entry is required and private unless you mark it otherwise. `=false` is a real default. `KEY=` has no default, and `@example` is documentation only.
+
+### Point the module at it
+
+```ts [nuxt.config.ts]
+export default defineNuxtConfig({
+ modules: ['nuxt-safe-runtime-config'],
+ safeRuntimeConfig: {
+ envSchema: '.env.example',
+ },
+})
+```
+
+### Read typed values
+
+```ts
+const config = useSafeRuntimeConfig()
+config.databaseUrl // string
+config.public.replayEnabled // boolean
+config.public.sampleRate // number
+config.public.logLevel // 'debug' | 'info' | 'warn' | 'error'
+config.requestLimit // number | undefined
+```
+
+The types come from the file during `nuxt prepare`. Your local `.env` is never read for them.
+
+::
+
+::caution
+Read your existing `.env.example` before you turn this on. `NUXT_API_SECRET=changeme` becomes a real default that ships in the build. Move placeholders to `@example`.
+::
+
+`envSchema` always validates at server start and never at build. `validateAtRuntime: false` is an error. Keep `onError` at `'throw'` so an invalid deployment refuses to start.
+
+The [env-spec reference](/reference/env-spec) lists every decorator, type and default rule.
+
+## Deploy one build with different values
+
+Build with the file present and no deployment variables. Then start the server with `NUXT_*` variables:
+
+```bash
+NUXT_DATABASE_URL=postgresql://db.internal/app \
+NUXT_API_SECRET=a-long-production-secret \
+NUXT_PUBLIC_REPLAY_ENABLED=true \
+node .output/server/index.mjs
+```
+
+The same `.output` can start again with other credentials and public settings, without a rebuild.
+
+The file owns every config path it declares. A value at one of those paths in `runtimeConfig`, or one inherited from the build environment, doesn't become a default, so a credential that CI happens to have never ends up in the build. Defaults written in the file are bundled, so leave credentials blank there.
+
+## Public keys
+
+A key reaches the browser only when it starts with `NUXT_PUBLIC_` and is marked `@public`. A `NUXT_` key marked `@public` stays private, because the annotation can't override Nuxt's prefix rule.
+
+## Nested config
+
+Keys become flat camelCase fields, so `NUXT_DATABASE_URL` is `databaseUrl`. To keep an existing nested shape, map keys to paths:
+
+```ts [nuxt.config.ts]
+export default defineNuxtConfig({
+ safeRuntimeConfig: {
+ envSchema: {
+ file: '.env.example',
+ paths: {
+ NUXT_PUBLIC_POSTHOG_REPLAY_SAMPLE_RATE: 'public.posthog.replaySampleRate',
+ },
+ },
+ },
+})
+```
+
+Each path must convert back to its key the way Nuxt maps `NUXT_*` variables, so `public.posthog.replaySampleRate` works and `public.replayRate` doesn't. A bad path fails with the file and line.
+
+Editing the file during `nuxt dev` restarts Nuxt.
+
+## Arrays and objects
+
+Declare the item and property types, and quote JSON defaults:
+
+```dotenv [.env.example]
+# @type=array(enum(read, write))
+NUXT_ROLES='["read"]'
+
+# @type=object(enabled=boolean, retries=number(min=0), tags=array(string))
+NUXT_SETTINGS='{"enabled":false,"retries":3,"tags":[]}'
+```
+
+`config.roles` is `('read' | 'write')[]`, and `config.settings` must have exactly `enabled`, `retries` and `tags`. JSON members are checked as written, so `"false"` inside the JSON stays a string and fails a `boolean` property.
+
+## How values are converted
+
+A string keeps its exact spelling. `NUXT_ACCOUNT_PIN=00123` declared as a string is `'00123'` after startup, even though Nitro 2 alone would parse it as `123`. On platforms that build each request's config themselves, a spelling the platform already parsed can't be recovered.
+
+A value that is present but invalid fails. It never falls back to the default.
+
+`process.env` keeps its `string | undefined` types, and `useRuntimeConfig()` keeps the types Nuxt infers. Only `useSafeRuntimeConfig()` has the declared types.
diff --git a/docs/content/1.guide/6.type-safety.md b/docs/content/1.guide/6.type-safety.md
deleted file mode 100644
index c832212..0000000
--- a/docs/content/1.guide/6.type-safety.md
+++ /dev/null
@@ -1,47 +0,0 @@
----
-title: Type safety
-description: Where the types of useSafeRuntimeConfig() come from, and when they change.
-navigation.icon: i-ph-shield-check
----
-
-`useRuntimeConfig()` infers its types from the defaults in `nuxt.config.ts`. A key you never gave a default does not exist in the types, a default of `''` makes it a `string` even when production leaves it unset, and a `0` default makes `NUXT_RATE=0.5` look like a `number` when it can arrive as a string.
-
-`useSafeRuntimeConfig()` is typed from the schema instead:
-
-```ts
-const config = useSafeRuntimeConfig()
-config.public.apiBase // string
-config.port // number | undefined, from optional(number())
-config.missingKey // type error
-```
-
-No generic is needed, in components, plugins, `server/api` or `server/utils`.
-
-## Where types come from
-
-| Schema source | Generated type |
-| --- | --- |
-| Inline `$schema` | Converted to JSON Schema, then to a TypeScript type |
-| Schema module (`$schema: './file'`) | The schema's input type, or its output type when `validateAtRuntime` is on |
-| `envSchema` | The declared `@type`, requiredness and visibility of each entry |
-
-Schema modules switch types because the transform only runs at runtime. Without runtime validation, an override such as `NUXT_PERF_TRACE_ENABLED=true` reaches your code untransformed, so the type is what the schema accepts. With runtime validation, the generated type describes the schema's output after successful validation.
-
-If validation fails with `onError: 'warn'` or `'ignore'`, `useSafeRuntimeConfig()` returns the raw config without applying transforms, even though the generated type still describes the schema's output. Keep `onError: 'throw'` (the default) to prevent invalid values from being returned under that output type.
-
-The declarations are written to `.nuxt/types/safe-runtime-config.d.ts` and included in the app and server TypeScript projects. Run `nuxi prepare` or restart `nuxt dev` after changing the schema. Never edit the generated file.
-
-## Server and client
-
-On the server, `useSafeRuntimeConfig()` returns the whole config. In the browser, Nuxt only ships `public`, so private keys are `undefined` at runtime even though the type lists them. Read private keys in `server/` only.
-
-```ts [server/utils/mailer.ts]
-export function createMailer() {
- const { smtp } = useSafeRuntimeConfig()
- return createTransport(smtp)
-}
-```
-
-## useRuntimeConfig keeps its types
-
-The module does not change the types of `useRuntimeConfig()`. Use the [ESLint rule](/integrations/eslint) to move call sites over to `useSafeRuntimeConfig()`.
diff --git a/docs/content/1.guide/7.eslint.md b/docs/content/1.guide/7.eslint.md
new file mode 100644
index 0000000..cf50727
--- /dev/null
+++ b/docs/content/1.guide/7.eslint.md
@@ -0,0 +1,49 @@
+---
+title: ESLint
+description: Find every untyped useRuntimeConfig() call and rewrite it to useSafeRuntimeConfig() with one eslint --fix.
+navigation.icon: simple-icons:eslint
+---
+
+After you add a schema, every existing `useRuntimeConfig()` call still returns the old, untyped config. The `prefer-safe-runtime-config` rule reports those calls, and its fix renames them to `useSafeRuntimeConfig()` with the same arguments:
+
+```ts
+const config = useRuntimeConfig(event) // reported
+const config = useSafeRuntimeConfig(event) // after --fix
+```
+
+## Set it up
+
+With [@nuxt/eslint](https://eslint.nuxt.com), the module registers the rule at `warn` as soon as it has a schema. There is nothing to add.
+
+Without it, add the recommended config, which also sets `warn`:
+
+```js [eslint.config.mjs]
+import { configs } from 'nuxt-safe-runtime-config/eslint'
+
+export default [
+ configs.recommended,
+]
+```
+
+To pick the severity, register the plugin yourself:
+
+```js [eslint.config.mjs]
+import safeRuntimeConfig from 'nuxt-safe-runtime-config/eslint'
+
+export default [
+ {
+ plugins: { 'safe-runtime-config': safeRuntimeConfig },
+ rules: { 'safe-runtime-config/prefer-safe-runtime-config': 'error' },
+ },
+]
+```
+
+## Migrate an app
+
+Run the fix once to move every call:
+
+```bash
+npx eslint --fix .
+```
+
+Then set the rule to `'error'`, so a new `useRuntimeConfig()` call fails CI.
diff --git a/docs/content/1.guide/7.nitro.md b/docs/content/1.guide/7.nitro.md
deleted file mode 100644
index 60adbb2..0000000
--- a/docs/content/1.guide/7.nitro.md
+++ /dev/null
@@ -1,33 +0,0 @@
----
-title: Nitro without Nuxt
-description: Validate runtime config in a standalone Nitro app.
-navigation.icon: i-ph-lightning
----
-
-Validation itself lives in a Nitro module, which the Nuxt module wraps. A Nitro app without Nuxt can use it directly, with Nitro 2 (`nitropack`) or Nitro 3.
-
-```ts [nitro.config.ts]
-import safeRuntimeConfig from 'nuxt-safe-runtime-config/nitro'
-import * as v from 'valibot'
-
-export default defineNitroConfig({
- modules: [safeRuntimeConfig],
- runtimeConfig: {
- databaseUrl: '',
- },
- safeRuntimeConfig: {
- $schema: v.object({
- databaseUrl: v.pipe(v.string(), v.url()),
- }),
- validateAtRuntime: true,
- },
-})
-```
-
-`safeRuntimeConfig` takes `$schema`, `validateAtBuild`, `validateAtRuntime`, `onError` and `jsonSchemaTarget`, with the same defaults as in Nuxt. A string `$schema` is resolved from the Nitro root.
-
-What differs from Nuxt:
-
-- `useSafeRuntimeConfig()` is not registered. With runtime validation on, the validated values are written into `useRuntimeConfig(event)` on Nitro 2 and into `useRuntimeConfig()` on Nitro 3. Nitro 2's shared `useRuntimeConfig()` is frozen and keeps the raw values.
-- The generated types are written to `/types/safe-runtime-config.d.ts` and declare a global `NuxtSafeRuntimeConfig` interface.
-- `envSchema` is Nuxt-only.
diff --git a/docs/content/1.guide/8.configuration.md b/docs/content/1.guide/8.configuration.md
deleted file mode 100644
index 28a97c3..0000000
--- a/docs/content/1.guide/8.configuration.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-title: Configuration
-description: Every safeRuntimeConfig option and its default.
-navigation.icon: i-ph-gear
----
-
-Options go under `safeRuntimeConfig` in `nuxt.config.ts`.
-
-```ts [nuxt.config.ts]
-export default defineNuxtConfig({
- modules: ['nuxt-safe-runtime-config'],
- safeRuntimeConfig: {
- $schema: runtimeConfigSchema,
- validateAtRuntime: true,
- },
-})
-```
-
-## Schema
-
-Set exactly one of `$schema` and `envSchema`. Without either, the module does nothing.
-
-::field-group
- ::field{name="$schema" type="StandardSchemaV1 | string"}
- A [Standard Schema](https://standardschema.dev/) object, or a project-relative path to a module that default-exports one. An inline schema must convert to JSON Schema. Use a path when the schema has transforms; see [Environment overrides](/guide/environment-overrides#transform-values-with-a-schema-module).
- ::
-
- ::field{name="envSchema" type="string | { file: string, paths?: Record }"}
- Experimental. Path to an annotated `.env.example`, or the path plus explicit config paths for nested keys. Turns on runtime validation. See [.env.example schemas](/guide/env-schema).
- ::
-::
-
-## Validation
-
-::field-group
- ::field{name="validateAtBuild" type="boolean" default="!validateAtRuntime"}
- Validate the `nuxt.config.ts` values during `nuxt dev` and `nuxt build`.
- ::
-
- ::field{name="validateAtRuntime" type="boolean" default="false"}
- Coerce and validate the config when the server starts and for each request config. Always on with `envSchema`.
- ::
-
- ::field{name="onError" type="'throw' | 'warn' | 'ignore'" default="'throw'"}
- What a failure does. See [When validation fails](/guide/validation#when-validation-fails).
- ::
-
- ::field{name="jsonSchemaTarget" type="'draft-2020-12' | 'draft-07' | 'openapi-3.0'" default="'draft-2020-12'"}
- The JSON Schema draft requested from your schema library. It is used for inline runtime validation, for coercion and for generated types. Change it only if your library cannot produce the default.
- ::
-::
-
-Inline schemas without native JSON Schema output are converted with [@standard-community/standard-json](https://github.com/standard-community/standard-json). The Valibot and Zod converters ship with the module, so the app does not install them.
diff --git a/docs/content/1.guide/8.nitro.md b/docs/content/1.guide/8.nitro.md
new file mode 100644
index 0000000..6848401
--- /dev/null
+++ b/docs/content/1.guide/8.nitro.md
@@ -0,0 +1,34 @@
+---
+title: Nitro without Nuxt
+description: Validate runtime config in a standalone Nitro 2 or Nitro 3 app with the Nitro module the Nuxt module is built on.
+navigation.icon: i-ph-lightning
+---
+
+The Nuxt module wraps a Nitro module that does the validation. A Nitro app without Nuxt can register it directly:
+
+```ts [nitro.config.ts]
+import safeRuntimeConfig from 'nuxt-safe-runtime-config/nitro'
+import * as v from 'valibot'
+
+export default defineNitroConfig({
+ modules: [safeRuntimeConfig],
+ runtimeConfig: {
+ databaseUrl: '',
+ },
+ safeRuntimeConfig: {
+ $schema: v.object({
+ databaseUrl: v.pipe(v.string(), v.url()),
+ }),
+ validateAtRuntime: true,
+ },
+})
+```
+
+It takes the same options as the Nuxt module, with the same defaults, except `envSchema`, which is Nuxt-only. A string `$schema` resolves from the Nitro root.
+
+Two things work differently without Nuxt:
+
+- There is no `useSafeRuntimeConfig()`. With runtime validation on, the validated values are written into `useRuntimeConfig(event)` on Nitro 2 and into `useRuntimeConfig()` on Nitro 3. On Nitro 2 the shared `useRuntimeConfig()` is frozen and keeps the raw values, so pass the event.
+- The types go to `/types/safe-runtime-config.d.ts` and declare a global `NuxtSafeRuntimeConfig` interface.
+
+The [Validation](/guide/validation) and [Environment variables](/guide/environment-overrides) pages apply here unchanged.
diff --git a/docs/content/1.guide/9.migrate-to-vitehub-env.md b/docs/content/1.guide/9.migrate-to-vitehub-env.md
index 524cab8..dfb4cb7 100644
--- a/docs/content/1.guide/9.migrate-to-vitehub-env.md
+++ b/docs/content/1.guide/9.migrate-to-vitehub-env.md
@@ -1,19 +1,19 @@
---
title: Migrate to ViteHub Env
-description: On Nuxt 5, move from this module to @vite-hub/env with one command.
+description: On Nuxt 5, replace this module with @vite-hub/env. A codemod rewrites the config and the call sites, and reports what it couldn't.
navigation.icon: i-ph-arrow-circle-up-right
---
-On Nuxt 5, use [ViteHub Env](https://vitehub.dev/docs/env) (`@vite-hub/env`) instead of this module. You still declare each value once and read it typed. What changes:
+On Nuxt 5, use [ViteHub Env](https://vitehub.dev/docs/env) (`@vite-hub/env`) instead of this module, which warns about it when you install or upgrade. You still declare each value once and read it typed. The differences:
-- **One API for Nuxt, Vite and Nitro.** Server code reads `useServerEnv(event)` and app code reads `usePublicEnv()`.
-- **Secrets stay sealed.** A secret is a `SecretEnv` that prints as `` until you call `.unseal()`.
-- **The same `.env.example`.** Env reads the same [`env-spec` profile](/guide/env-schema), so an `envSchema` app moves without changes to the file.
-- **Inspection from the CLI.** `vitehub env check` lists every declared variable and its status, and never prints values.
+- Server code reads `useServerEnv(event)` and app code reads `usePublicEnv()`, and the same API works in Vite and Nitro apps.
+- A secret is a `SecretEnv` that prints `` until you call `.unseal()`.
+- Env reads the same [`.env.example` format](/reference/env-spec), so an `envSchema` app keeps its file as it is.
+- `vitehub env check` lists every declared variable and whether it is set, without printing values.
## Run the codemod
-Upgrade to **Node.js 24.15 or newer** before running the codemod or installing the migrated dependencies. `vite-hub` requires it, even if your Nuxt 5 app currently runs on Node.js 22.
+The codemod and `vite-hub` need Node.js 24.15 or later, even if your app runs on Node.js 22 today. Upgrade first.
::steps
@@ -23,7 +23,7 @@ Upgrade to **Node.js 24.15 or newer** before running the codemod or installing t
npx @vite-hub/codemods nuxt-safe-runtime-config --dry-run
```
-`--dry-run` prints the diff of every file and a report, and writes nothing.
+`--dry-run` prints the diff for each file and the report, and writes nothing. Pass a directory as the last argument when the app isn't in the current one.
### Apply them
@@ -31,8 +31,6 @@ npx @vite-hub/codemods nuxt-safe-runtime-config --dry-run
npx @vite-hub/codemods nuxt-safe-runtime-config
```
-Pass a directory as the last argument when the app is not in the current directory.
-
### Install and check
```bash
@@ -40,17 +38,17 @@ pnpm install
npx nuxi prepare
```
-Then type-check the app and work through the follow-ups in the report.
+Then run your typecheck and work through the [follow-ups](#follow-ups) in the report.
::
-## What it changes
+## What the codemod changes
-In `nuxt.config.ts`, the codemod replaces `nuxt-safe-runtime-config` with `vite-hub/nuxt` in `modules`. It moves the declarations to `vitehub.env` and removes `safeRuntimeConfig`. `package.json` drops this module and adds `vite-hub`.
+In `nuxt.config.ts` it replaces `nuxt-safe-runtime-config` with `vite-hub/nuxt` in `modules`, moves your declarations to `vitehub.env` and removes `safeRuntimeConfig`. In `package.json` it removes this module and adds `vite-hub`.
-### With `envSchema`
+### An `envSchema` app
-The `.env.example` stays as it is. `prefix: 'NUXT_'` keeps the same variable names and the same `public` split.
+The `.env.example` stays as it is. `prefix: 'NUXT_'` keeps the variable names and the same public split:
```ts [nuxt.config.ts]
import { envSchema } from '@vite-hub/env/vite'
@@ -64,9 +62,9 @@ export default defineNuxtConfig({
})
```
-### With `$schema`
+### A `$schema` app
-The codemod loads your schema, converts it to JSON Schema, and writes one Env declaration per value. Each value keeps its `NUXT_*` variable name, and literal defaults stay.
+The codemod loads your schema, converts it to JSON Schema and writes one Env declaration per value. Each value keeps its `NUXT_*` name, and literal defaults stay.
::code-group
@@ -114,9 +112,9 @@ export default defineNuxtConfig({
::
-Server fields with credential-like names (`secret`, `token`, `password`, `key`, database URLs) become `secret: true`.
+Server fields with credential-like names, such as `secret`, `token`, `password`, `key` or a database URL, become `secret: true`.
-### In your code
+### Your code
```ts [server/api/config.get.ts]
// Before
@@ -129,19 +127,19 @@ const config = useServerEnv(event)
In app code, `useSafeRuntimeConfig()` becomes `usePublicEnv()` from `#vitehub/env/public`, and `config.public.apiBase` becomes `config.apiBase`.
-## Follow-ups
+::warning
+Env fixes public values at build time. This module applied `NUXT_PUBLIC_*` overrides when the server started, so set those variables before you build. Server values are still read when the server runs.
+::
-The report lists each change the codemod could not make, with `file:line`:
+## Follow-ups
-- **Secret reads.** `config.apiSecret` is now a `SecretEnv`. Call `.unseal()` where the code needs the raw value.
-- **Lost checks.** Code-first Env declarations do not keep minimum lengths, patterns, URL formats, transforms or refinements. Check those values in code, or move to a `.env.example` with `envSchema()`, which keeps length, range, integer and URL checks.
-- **JSON arrays, objects and unions.** These stay in `runtimeConfig`. Read them with `useRuntimeConfig()`, or declare them in a `.env.example`.
-- **The deployment preset.** `vite-hub/nuxt` needs one. The codemod copies `nitro.preset` when it can, and otherwise sets `node`.
-- **Call sites it did not rewrite.** For example, a config object passed to another function, or `useRuntimeConfig()` reads of keys that moved.
-- **The ESLint rule.** Remove `nuxt-safe-runtime-config/eslint` from your ESLint config.
+The report lists each change the codemod couldn't make, with its `file:line`:
-::warning
-Public Env values are fixed at build time. Nuxt applied `NUXT_PUBLIC_*` overrides when the server started; with Env, set them before you build. Server Env values are still read when the server runs.
-::
+- `config.apiSecret` is now a `SecretEnv`. Call `.unseal()` where the code needs the raw value.
+- Code-first Env declarations drop minimum lengths, patterns, URL formats, transforms and refinements. Check those values in code, or move to a `.env.example` with `envSchema()`, which keeps length, range, integer and URL checks.
+- JSON arrays, objects and unions stay in `runtimeConfig`. Read them with `useRuntimeConfig()`, or declare them in a `.env.example`.
+- `vite-hub/nuxt` needs a deployment preset. The codemod copies `nitro.preset` when it can, and sets `node` otherwise.
+- Calls it couldn't follow, such as a config object passed to another function, or a `useRuntimeConfig()` read of a key that moved.
+- `nuxt-safe-runtime-config/eslint` in your ESLint config, which you remove by hand.
-Shelve and the [standalone Nitro module](/guide/nitro) are not part of the codemod.
+The codemod doesn't cover the [standalone Nitro module](/guide/nitro).
diff --git a/docs/content/2.reference/1.configuration.md b/docs/content/2.reference/1.configuration.md
new file mode 100644
index 0000000..0a7b5da
--- /dev/null
+++ b/docs/content/2.reference/1.configuration.md
@@ -0,0 +1,46 @@
+---
+title: Configuration
+description: Every safeRuntimeConfig option with its type and default, the useSafeRuntimeConfig() signature, and the package entry points.
+navigation.icon: i-ph-gear
+---
+
+## Options
+
+Options go under `safeRuntimeConfig` in `nuxt.config.ts`. Set `$schema` or `envSchema`, not both. With neither, the module does nothing.
+
+```ts [nuxt.config.ts]
+export default defineNuxtConfig({
+ modules: ['nuxt-safe-runtime-config'],
+ safeRuntimeConfig: {
+ $schema: runtimeConfigSchema,
+ validateAtRuntime: true,
+ },
+})
+```
+
+| Option | Type | Default | What it does |
+| --- | --- | --- | --- |
+| `$schema` | `StandardSchemaV1 \| string` | | A [Standard Schema](https://standardschema.dev/), or a path from the project root to a module that default-exports one. Use a path for [transforms and refinements](/guide/environment-overrides#transform-values-with-a-schema-module). |
+| `envSchema` | `string \| { file: string, paths?: Record }` | | Experimental. An annotated [`.env.example`](/guide/env-schema), with optional [nested paths](/guide/env-schema#nested-config). Turns on `validateAtRuntime`. |
+| `validateAtBuild` | `boolean` | `!validateAtRuntime` | Check the `nuxt.config.ts` values during `nuxt dev` and `nuxt build`. |
+| `validateAtRuntime` | `boolean` | `false` | Convert and check the config when the server starts, and each request's config when it differs. Always on with `envSchema`, and `false` there is an error. |
+| `onError` | `'throw' \| 'warn' \| 'ignore'` | `'throw'` | What a failed check does. See [When a check fails](/guide/validation#when-a-check-fails). |
+| `jsonSchemaTarget` | `'draft-2020-12' \| 'draft-07' \| 'openapi-3.0'` | `'draft-2020-12'` | The JSON Schema draft requested from your schema library for runtime checks, coercion and types. Change it only if your library can't produce the default. |
+
+When a library has no JSON Schema output of its own, the module converts it with [@standard-community/standard-json](https://github.com/standard-community/standard-json). The converters for Valibot and Zod ship with the module, so you don't install them.
+
+## `useSafeRuntimeConfig()`
+
+```ts
+function useSafeRuntimeConfig(event?: { context: object }): SafeRuntimeConfig
+```
+
+Auto-imported in the app and in `server/`, and importable from `#imports`. Without an event it returns the app's config. With an H3 event it returns that request's config, the checked version of `useRuntimeConfig(event)`. The return type comes from `.nuxt/types/safe-runtime-config.d.ts`, described in [Types](/guide/type-safety).
+
+## Entry points
+
+| Import | What it is |
+| --- | --- |
+| `nuxt-safe-runtime-config` | The Nuxt module |
+| `nuxt-safe-runtime-config/nitro` | The [Nitro module](/guide/nitro), for Nitro apps without Nuxt |
+| `nuxt-safe-runtime-config/eslint` | The [ESLint plugin](/guide/eslint) and its `configs.recommended` |
diff --git a/docs/content/2.reference/2.env-spec.md b/docs/content/2.reference/2.env-spec.md
new file mode 100644
index 0000000..008fbdc
--- /dev/null
+++ b/docs/content/2.reference/2.env-spec.md
@@ -0,0 +1,108 @@
+---
+title: env-spec syntax
+description: Every decorator, type and default rule envSchema accepts in .env.example, and the syntax it rejects.
+navigation.icon: i-ph-file-text
+---
+
+`envSchema` reads a `.env.example` written in the `env-spec-v1` profile: the [@env-spec syntax](https://varlock.dev/env-spec/reference/) with a small set of [Varlock decorators](https://varlock.dev/reference/item-decorators/). It is not the full Varlock runtime. The file declares names, types, descriptions, defaults, and whether each value is required and public. It never reads `.env`, fetches secrets or evaluates expressions.
+
+```dotenv [.env.example]
+# @defaultRequired=true @defaultSensitive=true
+# ---
+
+# Database connection supplied by the deployment.
+# @type=url @example="https://database.example.test"
+NUXT_DATABASE_URL=
+
+# @type=number(min=1, max=65535, isInt=true)
+NUXT_SMTP_PORT=587
+
+# @type=enum(debug, info, warn, error) @public
+NUXT_PUBLIC_LOG_LEVEL=info
+
+# @optional @public
+NUXT_PUBLIC_BANNER=
+```
+
+[.env.example as schema](/guide/env-schema) shows how the module maps these entries to runtime config.
+
+## Header
+
+An optional header sets defaults for every entry and ends with `# ---`. It accepts two decorators, both `true` by default:
+
+| Decorator | Meaning |
+| --- | --- |
+| `@defaultRequired=false` | Entries are optional unless marked `@required` |
+| `@defaultSensitive=false` | Entries are public unless marked `@sensitive` |
+
+## Entries
+
+A name matches `[A-Za-z_][A-Za-z0-9_]*` and is at most 256 characters. Duplicate names fail, and so do `__proto__`, `prototype` and `constructor` in any case.
+
+The comment lines right above an entry become its description. A blank line or a divider ends it, and a comment that looks like a disabled assignment, such as `# OLD_KEY=1`, is left out. Decorators can share a comment line.
+
+| Decorator | Meaning |
+| --- | --- |
+| `@type=…` | The value's type. See [Types](#types). Without it, the value is a string. |
+| `@required`, `@required=false` | The value must be present and not empty. |
+| `@optional`, `@optional=false` | The inverse of `@required`. Use one or the other. |
+| `@sensitive`, `@sensitive=false` | The value must stay private. |
+| `@public`, `@public=false` | The inverse of `@sensitive`. Use one or the other. A key still needs the `NUXT_PUBLIC_` prefix to reach the browser. |
+| `@example="sample"` | Documentation. It never becomes a default. |
+
+A repeated decorator, an unknown one, or a conflicting pair such as `@required @optional` fails with the file and line.
+
+## Types
+
+| `@type` | Value |
+| --- | --- |
+| `string` | A string. Optional bounds: `string(minLength=1, maxLength=80)`. |
+| `number` | A finite number. Optional bounds: `number(min=0, max=100, isInt=true)`. |
+| `boolean` | `true` or `false`. |
+| `enum(debug, info, error)` | One of the listed strings. Quote a choice that looks like a number or a boolean. |
+| `url` | An absolute URI, checked with the JSON Schema `uri` format. The value stays a string. |
+| `array`, `array(string)` | A JSON array, with an optional item type. |
+| `object`, `object(enabled=boolean, retries=number)` | A JSON object. With properties, it must have exactly those. Bare `object` accepts any JSON object, and `object()` only an empty one. |
+
+Types nest, as in `array(object(name=string, roles=array(enum(read, write))))`, up to 16 levels.
+
+The assigned value never sets the type. `TOKEN=00123` and `FLAG=true` are both strings unless `@type` says otherwise.
+
+## Defaults
+
+| Written as | Means |
+| --- | --- |
+| `KEY=value` | `value` is the default |
+| `KEY=` | No default |
+| `KEY=""` | The default is an empty string |
+| `KEY='["read"]'` | A JSON default for an array or object, in quotes |
+
+This is stricter than the usual tools. [dotenv-safe](https://www.npmjs.com/package/dotenv-safe) treats example values as documentation, and dotenv reads `KEY=` as an empty string. Here an assigned value ships as a real default, so a placeholder like `changeme` belongs in `@example`.
+
+Each default is checked against its type when the module reads the file, and a bad one fails with the file, line and key:
+
+| Type | Accepted default |
+| --- | --- |
+| `string` | Anything. It keeps its exact content, including leading zeros and whitespace inside quotes. |
+| `number` | Decimal notation, with exponents. Not hexadecimal, `NaN` or `Infinity`. Surrounding whitespace is trimmed. |
+| `boolean` | `true`, `false`, `1` or `0`. Surrounding whitespace is trimmed. |
+| `enum` | One of the listed choices. |
+| `url` | A URI exactly as written, with no surrounding whitespace. Use Punycode for international hostnames, such as `https://xn--r8jz45g.xn--zckzah` for `https://例え.テスト`, and percent-encode spaces and non-ASCII path characters. The same rule applies at server start. |
+| `array`, `object` | Quoted JSON whose members already match their types. Members are never converted, so `"false"` fails a `boolean` property. |
+
+## Empty values
+
+On a required entry, `KEY=""` fails when the module reads the file, and an empty value at server start fails validation. An optional string keeps `""`. For any other optional type, empty means unset, so starting the server with `NUXT_REQUEST_LIMIT=` for an `@optional @type=number` entry gives `undefined`.
+
+## Rejected syntax
+
+The module rejects anything it can't check statically, instead of declaring a type it can't enforce:
+
+- `$VAR` and `${VAR}` references. Single quotes or `\$` make them literal text.
+- `$(command)` substitutions and calls such as `fetchSecret(ref)`
+- unquoted `[a, b]` and `{key=value}` values. Quote JSON defaults instead.
+- dynamic decorator values such as `@required=forEnv(production)`
+- custom types and unknown type arguments
+- JSON nested deeper than 64 levels, and the keys `__proto__`, `prototype`, `constructor` and `__envSchemaUnset` in any JSON object
+
+Error messages give the file, line, key and reason. They never include an assigned value.
diff --git a/docs/content/2.schemas/1.index.md b/docs/content/2.schemas/1.index.md
deleted file mode 100644
index d9de0ab..0000000
--- a/docs/content/2.schemas/1.index.md
+++ /dev/null
@@ -1,57 +0,0 @@
----
-title: Schema libraries
-description: Use any Standard Schema library for $schema.
-navigation.icon: i-ph-brackets-curly
----
-
-`$schema` accepts any library that implements [Standard Schema](https://standardschema.dev/). The module validates through the shared `~standard` interface, so switching libraries means rewriting the schema, not the config.
-
-::code-group
-
-```ts [Valibot]
-import * as v from 'valibot'
-
-const schema = v.object({
- apiKey: v.string(),
- port: v.optional(v.number()),
-})
-```
-
-```ts [Zod]
-import { z } from 'zod'
-
-const schema = z.object({
- apiKey: z.string(),
- port: z.number().optional(),
-})
-```
-
-```ts [ArkType]
-import { type } from 'arktype'
-
-const schema = type({
- 'apiKey': 'string',
- 'port?': 'number',
-})
-```
-
-::
-
-Build validation runs your library as written. For runtime validation and generated types, an inline schema is converted to JSON Schema, so it must use features JSON Schema can express. Transforms, custom refinements and other code-only checks belong in a [schema module](/guide/environment-overrides#transform-values-with-a-schema-module), which the server runs as written.
-
-## Guides
-
-::card-group
- :::card{title="Valibot" icon="custom:valibot" to="/schemas/valibot"}
- :::
-
- :::card{title="Zod" icon="simple-icons:zod" to="/schemas/zod"}
- :::
-
- :::card{title="ArkType" icon="custom:arktype" to="/schemas/arktype"}
- :::
-
- :::card{title="env-spec profile" icon="i-ph-file-text" to="/schemas/env-spec"}
- The `.env.example` syntax used by `envSchema`.
- :::
-::
diff --git a/docs/content/2.schemas/2.valibot.md b/docs/content/2.schemas/2.valibot.md
deleted file mode 100644
index 952496c..0000000
--- a/docs/content/2.schemas/2.valibot.md
+++ /dev/null
@@ -1,60 +0,0 @@
----
-title: Valibot
-description: Write the runtime config schema with Valibot.
-navigation.icon: custom:valibot
----
-
-[Valibot](https://valibot.dev/) 1.x implements Standard Schema natively.
-
-```bash
-pnpm add valibot
-```
-
-```ts [nuxt.config.ts]
-import * as v from 'valibot'
-
-export default defineNuxtConfig({
- modules: ['nuxt-safe-runtime-config'],
- runtimeConfig: {
- databaseUrl: '',
- smtp: { host: '', port: 587 },
- public: { apiBase: 'https://api.example.com', logLevel: 'info' },
- },
- safeRuntimeConfig: {
- $schema: v.object({
- databaseUrl: v.pipe(v.string(), v.url()),
- smtp: v.object({
- host: v.pipe(v.string(), v.minLength(1)),
- port: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)),
- }),
- public: v.object({
- apiBase: v.pipe(v.string(), v.url()),
- logLevel: v.picklist(['debug', 'info', 'warn', 'error']),
- }),
- }),
- },
-})
-```
-
-## Patterns
-
-```ts
-v.object({
- // required and optional
- secret: v.pipe(v.string(), v.minLength(32)),
- sentryDsn: v.optional(v.pipe(v.string(), v.url())),
- timeout: v.optional(v.number(), 5000),
-
- // enums and lists
- region: v.picklist(['eu', 'us']),
- allowedOrigins: v.array(v.pipe(v.string(), v.url())),
-
- // formats
- adminEmail: v.pipe(v.string(), v.email()),
- slug: v.pipe(v.string(), v.regex(/^[a-z-]+$/)),
-})
-```
-
-With `validateAtRuntime`, `v.number()`, `v.boolean()`, `v.picklist()` and `v.array()` accept the matching `NUXT_*` strings through [coercion](/guide/environment-overrides#coercion). No `v.transform()` is needed for them.
-
-For `v.transform()` or a `v.check()` across fields, move the schema into a [schema module](/guide/environment-overrides#transform-values-with-a-schema-module).
diff --git a/docs/content/2.schemas/3.zod.md b/docs/content/2.schemas/3.zod.md
deleted file mode 100644
index a644891..0000000
--- a/docs/content/2.schemas/3.zod.md
+++ /dev/null
@@ -1,60 +0,0 @@
----
-title: Zod
-description: Write the runtime config schema with Zod.
-navigation.icon: simple-icons:zod
----
-
-[Zod](https://zod.dev/) 3.24+ and 4 implement Standard Schema. The examples use Zod 4.
-
-```bash
-pnpm add zod
-```
-
-```ts [nuxt.config.ts]
-import { z } from 'zod'
-
-export default defineNuxtConfig({
- modules: ['nuxt-safe-runtime-config'],
- runtimeConfig: {
- databaseUrl: '',
- smtp: { host: '', port: 587 },
- public: { apiBase: 'https://api.example.com', logLevel: 'info' },
- },
- safeRuntimeConfig: {
- $schema: z.object({
- databaseUrl: z.url(),
- smtp: z.object({
- host: z.string().min(1),
- port: z.int().min(1).max(65535),
- }),
- public: z.object({
- apiBase: z.url(),
- logLevel: z.enum(['debug', 'info', 'warn', 'error']),
- }),
- }),
- },
-})
-```
-
-## Patterns
-
-```ts
-z.object({
- // required and optional
- secret: z.string().min(32),
- sentryDsn: z.url().optional(),
- timeout: z.number().default(5000),
-
- // enums and lists
- region: z.enum(['eu', 'us']),
- allowedOrigins: z.array(z.url()),
-
- // formats
- adminEmail: z.email(),
- slug: z.string().regex(/^[a-z-]+$/),
-})
-```
-
-With `validateAtRuntime`, `z.number()`, `z.boolean()`, `z.enum()` and `z.array()` accept the matching `NUXT_*` strings through [coercion](/guide/environment-overrides#coercion). `z.coerce` is not needed, and turns `'false'` into `true`.
-
-For `.transform()`, `.refine()` or `.superRefine()`, move the schema into a [schema module](/guide/environment-overrides#transform-values-with-a-schema-module).
diff --git a/docs/content/2.schemas/4.arktype.md b/docs/content/2.schemas/4.arktype.md
deleted file mode 100644
index 128fd4a..0000000
--- a/docs/content/2.schemas/4.arktype.md
+++ /dev/null
@@ -1,60 +0,0 @@
----
-title: ArkType
-description: Write the runtime config schema with ArkType.
-navigation.icon: custom:arktype
----
-
-[ArkType](https://arktype.io/) 2.x implements Standard Schema and writes types in TypeScript-like strings.
-
-```bash
-pnpm add arktype
-```
-
-```ts [nuxt.config.ts]
-import { type } from 'arktype'
-
-export default defineNuxtConfig({
- modules: ['nuxt-safe-runtime-config'],
- runtimeConfig: {
- databaseUrl: '',
- smtp: { host: '', port: 587 },
- public: { apiBase: 'https://api.example.com', logLevel: 'info' },
- },
- safeRuntimeConfig: {
- $schema: type({
- databaseUrl: 'string.url',
- smtp: {
- host: 'string > 0',
- port: '1 <= number.integer <= 65535',
- },
- public: {
- apiBase: 'string.url',
- logLevel: '\'debug\' | \'info\' | \'warn\' | \'error\'',
- },
- }),
- },
-})
-```
-
-## Patterns
-
-```ts
-type({
- // required and optional
- 'secret': 'string >= 32',
- 'sentryDsn?': 'string.url',
- 'timeout': 'number = 5000',
-
- // enums and lists
- 'region': '\'eu\' | \'us\'',
- 'allowedOrigins': 'string.url[]',
-
- // formats
- 'adminEmail': 'string.email',
- 'slug': /^[a-z-]+$/,
-})
-```
-
-With `validateAtRuntime`, `number`, `boolean`, string unions and arrays accept the matching `NUXT_*` strings through [coercion](/guide/environment-overrides#coercion).
-
-For morphs (`.pipe()`, `string.numeric.parse`) or `.narrow()`, move the schema into a [schema module](/guide/environment-overrides#transform-values-with-a-schema-module).
diff --git a/docs/content/2.schemas/5.env-spec.md b/docs/content/2.schemas/5.env-spec.md
deleted file mode 100644
index 203d954..0000000
--- a/docs/content/2.schemas/5.env-spec.md
+++ /dev/null
@@ -1,84 +0,0 @@
----
-title: env-spec profile
-description: The env-spec-v1 syntax that envSchema reads from a committed .env.example.
-navigation.icon: i-ph-file-text
----
-
-The `env-spec-v1` profile treats a committed `.env.example` as a shared schema. Enabling the feature is explicit. Existing example files keep their usual meaning until the feature is enabled.
-
-The file owns names, descriptions, types, requiredness, sensitivity and defaults. Framework adapters own loading, public prefixes and runtime validation. The profile does not read `.env`, fetch secrets or evaluate expressions.
-
-```dotenv
-# @defaultRequired=true @defaultSensitive=true
-# ---
-
-# Database connection supplied by the deployment environment.
-# @type=url @example="https://database.example.test"
-DATABASE_URL=
-
-# @type=number(min=1, max=65535, isInt=true) @public
-PORT=3000
-
-# @type=boolean @public
-ENABLE_SEARCH=false
-
-# @type=enum(debug, info, warn, error) @public
-LOG_LEVEL=info
-
-# @optional @public
-OPTIONAL_LABEL=
-```
-
-This reuses [@env-spec syntax](https://varlock.dev/env-spec/reference/) and a restricted set of [Varlock decorators](https://varlock.dev/reference/item-decorators/). It defines its own named semantic profile. The syntax specification alone does not define decorator meanings, and this profile does not implement the full Varlock runtime.
-
-## Declarations and metadata
-
-Names follow `[A-Za-z_][A-Za-z0-9_]*`. Duplicate names, names longer than 256 characters and the names `__proto__`, `prototype` and `constructor`, ignoring case, are rejected. Definitions preserve source filename and declaration line.
-
-Comments directly before a declaration become its description. Blank lines and dividers end attachment. Comments that look like disabled assignments are excluded from descriptions. Inline comments and single or double quoted values follow the upstream parser. Decorators may share a comment line. Duplicate decorators, unsupported decorators and conflicting aliases are errors.
-
-Root decorators must be in a header ending with `# ---`. Only `@defaultRequired` and `@defaultSensitive` are supported there, both with static boolean values. Both default to `true`. An item can override those defaults.
-
-| Item decorator | Meaning |
-| --- | --- |
-| `@type=string` | String output. This is always the default type. |
-| `@type=string(minLength=1, maxLength=80)` | Inclusive string length constraints. |
-| `@type=number(min=0, max=100, isInt=true)` | Finite numeric output with optional bounds and safe integer constraint. |
-| `@type=boolean` | Boolean output. |
-| `@type=enum(debug, info, error)` | One of the listed strings. Quote numeric or boolean-looking choices. |
-| `@type=array(string)` | JSON array with an optional nested item type. Bare `array` accepts any JSON items. |
-| `@type=object(enabled=boolean, retries=number)` | JSON object with an exact required property shape. Bare `object` accepts any safe JSON object. |
-| `@type=url` | An absolute URI accepted by the JSON Schema `uri` format. Output remains a string. |
-| `@required` / `@required=false` | Whether a resolved value must be present and nonempty. |
-| `@optional` / `@optional=false` | Inverse of `@required`. Do not combine both decorators. |
-| `@sensitive` / `@sensitive=false` | Whether the field must remain private. |
-| `@public` / `@public=false` | Inverse of `@sensitive`. Do not combine both decorators. |
-| `@example="sample"` | Documentation only. Never supplies a runtime default. |
-
-No type is inferred from assignment values or developer environment files. For example, `TOKEN=00123` and `FLAG=true` both declare strings unless `@type` says otherwise. String defaults preserve their lexical contents, including leading zeroes.
-
-## Defaults, missing values and empty strings
-
-A nonempty assignment is a real default. `KEY=` declares no default. `KEY=""` explicitly declares an empty string. This differs from [dotenv-safe](https://www.npmjs.com/package/dotenv-safe), which uses example values only as documentation, and from ordinary dotenv loaders, which parse `KEY=` as an empty string.
-
-Use `@example` for a placeholder. Copying an existing `.env.example` into this feature without reviewing its assignment values can turn placeholders into defaults.
-
-Defaults are checked against the declared type and constraints. Invalid defaults fail with the filename, line and key. A present invalid runtime override must fail rather than silently falling back to a default.
-
-Required strings reject an explicit empty default. Optional strings preserve an explicit empty default. For optional number, boolean, enum, URL, array and object fields, an explicit empty default means no default. Framework adapters must normalize an empty runtime input for those optional types to `undefined` before applying a default or validating. They must preserve `""` for optional strings. Required runtime empty inputs fail validation.
-
-Numeric defaults accept finite decimal notation, including exponents, and reject hexadecimal, `NaN` and `Infinity`. Boolean defaults accept `true`, `false`, `1` and `0`. Whitespace inside quoted values is preserved for strings; typed numeric and boolean conversion trims it.
-
-URL defaults and runtime values use the same `uri` format from `@cfworker/json-schema`, including nested JSON members. Values are validated as written, without platform URL normalization. Use Punycode for internationalized hostnames and percent encoding for spaces or non-ASCII path characters; surrounding whitespace is rejected. For example, use `https://xn--r8jz45g.xn--zckzah` instead of `https://例え.テスト`.
-
-## Boundaries and unsupported syntax
-
-The parser returns serializable metadata. It does not modify `process.env`, generate declarations or publish values to the browser. `process.env.PORT` remains `string | undefined`. A validated output may be `number` only after the framework adapter converts and checks the actual input.
-
-Public metadata does not replace a framework's exposure rules. A Nuxt adapter must still enforce `NUXT_PUBLIC_` and prevent sensitive values from entering public runtime config. The same metadata can inform a Vite adapter without sharing Nuxt's environment reader.
-
-Arrays and objects use quoted JSON defaults, such as `KEY='[1,2]'` and `KEY='{"enabled":true}'`. Nested item/property declarations use the same static type syntax, for example `array(object(name=string, roles=array(enum(read, write))))`. Object shapes have required properties and reject additional properties. `object()` accepts only an empty object. JSON members must already match their declared types and are never coerced. Reserved prototype keys and the internal `__envSchemaUnset` key are rejected at every JSON object level. Type nesting is limited to 16 levels and JSON value nesting to 64 levels.
-
-Expansions, shell commands, secret-provider functions, dynamic decorators, custom types and unknown type arguments are rejected. Static type constraint calls, enum declarations and nested array/object types are accepted. Unsupported syntax fails instead of producing declarations that promise unchecked runtime values.
-
-Errors contain locations and rule names, never assignment values or the upstream parser's source excerpt.
diff --git a/docs/content/3.integrations/1.index.md b/docs/content/3.integrations/1.index.md
deleted file mode 100644
index d34fd00..0000000
--- a/docs/content/3.integrations/1.index.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-title: Integrations
-description: Tools that work with Nuxt Safe Runtime Config.
-navigation.icon: i-ph-puzzle-piece
----
-
-::card-group
- :::card{title="ESLint" icon="simple-icons:eslint" to="/integrations/eslint"}
- Flag `useRuntimeConfig()` calls and fix them to `useSafeRuntimeConfig()`.
- :::
-::
diff --git a/docs/content/3.integrations/3.eslint.md b/docs/content/3.integrations/3.eslint.md
deleted file mode 100644
index d77b209..0000000
--- a/docs/content/3.integrations/3.eslint.md
+++ /dev/null
@@ -1,49 +0,0 @@
----
-title: ESLint
-description: Flag useRuntimeConfig() calls and replace them with useSafeRuntimeConfig().
-navigation.icon: simple-icons:eslint
----
-
-The `prefer-safe-runtime-config` rule reports every `useRuntimeConfig()` call. Its fix renames the call to `useSafeRuntimeConfig()` and keeps the arguments, so `useRuntimeConfig(event)` becomes `useSafeRuntimeConfig(event)`.
-
-```ts
-const config = useRuntimeConfig() // reported
-const config = useSafeRuntimeConfig() // ok
-```
-
-## Setup
-
-With [@nuxt/eslint](https://eslint.nuxt.com), the rule is registered at `warn` when the module has a schema. Nothing to configure.
-
-Without it, add the recommended config:
-
-```js [eslint.config.mjs]
-import { configs } from 'nuxt-safe-runtime-config/eslint'
-
-export default [
- configs.recommended,
-]
-```
-
-Or register the plugin and pick the severity:
-
-```js [eslint.config.mjs]
-import safeRuntimeConfig from 'nuxt-safe-runtime-config/eslint'
-
-export default [
- {
- plugins: { 'safe-runtime-config': safeRuntimeConfig },
- rules: { 'safe-runtime-config/prefer-safe-runtime-config': 'error' },
- },
-]
-```
-
-## Migrate an app
-
-Run the fix once to move every call site:
-
-```bash
-npx eslint --fix .
-```
-
-Then set the rule to `'error'` so new calls fail CI.
diff --git a/docs/content/index.md b/docs/content/index.md
index 3e6dd56..af62aac 100644
--- a/docs/content/index.md
+++ b/docs/content/index.md
@@ -9,44 +9,45 @@ navigation: false
::u-page-section
---
-title: What it checks
+title: One schema, checked where your values come from
+description: Write the schema once. The module checks it against nuxt.config.ts at build, or against the NUXT_* variables the server starts with, and types useSafeRuntimeConfig() from it.
---
#features
:::u-page-feature
---
icon: i-ph-hammer
- title: Build validation
- to: /guide/validation
+ title: At build
+ to: /guide/validation#at-build
---
- Checks the values in `nuxt.config.ts` during `nuxt dev` and `nuxt build`.
+ `nuxt build` stops when a value in `nuxt.config.ts` is missing or malformed.
:::
:::u-page-feature
---
icon: i-ph-cloud-check
- title: Runtime validation
- to: /guide/validation
+ title: At runtime
+ to: /guide/validation#at-server-start
---
- Checks the values the deployed server starts with, after `NUXT_*` overrides.
+ With `validateAtRuntime`, invalid `NUXT_*` values stop startup with synchronous schemas or fail requests with asynchronous schemas.
:::
:::u-page-feature
---
icon: i-ph-arrows-left-right
- title: Environment coercion
+ title: NUXT_* strings converted
to: /guide/environment-overrides
---
- Turns `NUXT_FLAG=true` into `true` and `NUXT_RATE=0.5` into `0.5` when the schema asks for them.
+ `NUXT_FLAG=false` becomes `false` and `NUXT_RATE=0.5` becomes `0.5` when the schema asks for them.
:::
:::u-page-feature
---
icon: i-ph-shield-check
- title: Generated types
+ title: Typed from the schema
to: /guide/type-safety
---
- `useSafeRuntimeConfig()` is typed from your schema in pages, plugins and server routes.
+ `useSafeRuntimeConfig()` has your schema's types in pages, plugins and server routes.
:::
:::u-page-feature
@@ -55,15 +56,15 @@ title: What it checks
title: .env.example as schema
to: /guide/env-schema
---
- Annotate a committed `.env.example` and build without deployment secrets.
+ Add `@type` comments to the file you already commit, and build without secrets.
:::
:::u-page-feature
---
icon: simple-icons:eslint
- title: ESLint rule
- to: /integrations/eslint
+ title: One-command migration
+ to: /guide/eslint
---
- Flags `useRuntimeConfig()` calls and fixes them to `useSafeRuntimeConfig()`.
+ `eslint --fix` rewrites every `useRuntimeConfig()` call to `useSafeRuntimeConfig()`.
:::
::
diff --git a/docs/nuxt.config.ts b/docs/nuxt.config.ts
index 67360af..c0eac7f 100644
--- a/docs/nuxt.config.ts
+++ b/docs/nuxt.config.ts
@@ -6,4 +6,12 @@ export default defineNuxtConfig({
docus: {
assistant: { enabled: false },
},
+ routeRules: {
+ '/guide/configuration': { redirect: '/reference/configuration' },
+ '/schemas': { redirect: '/guide/installation' },
+ '/schemas/**': { redirect: '/guide/installation' },
+ '/schemas/env-spec': { redirect: '/reference/env-spec' },
+ '/integrations': { redirect: '/guide/eslint' },
+ '/integrations/eslint': { redirect: '/guide/eslint' },
+ },
})