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
1 change: 1 addition & 0 deletions .github/workflows/pkg.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ jobs:
run: |
test ! -L dist/runtime
test -f dist/runtime/composables/useSafeRuntimeConfig.js
test -f dist/runtime/nitro/validate-plugin.js
- run: pnpm dlx pkg-pr-new publish --pnpm
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ Validate Nuxt runtime config with <b>Valibot</b>, <b>Zod</b>, <b>ArkType</b> or
</p>
</p>

> [!TIP]
> On Nuxt 5, use [ViteHub Env](https://vitehub.dev/docs/env). Migrate with `npx @vite-hub/codemods nuxt-safe-runtime-config`. See the [migration guide](https://nuxt-safe-runtime-config.onmax.me/guide/migrate-to-vitehub-env).

`useRuntimeConfig()` returns whatever ends up in runtime config. Nothing checks that `NUXT_DATABASE_URL` is set or that `NUXT_PUBLIC_REPLAY_ENABLED=false` arrives as `false`. This module validates runtime config against a schema at build time or when the server starts, and `useSafeRuntimeConfig()` returns the values typed from that schema.

## Quick start
Expand Down
15 changes: 15 additions & 0 deletions docs/app/components/app/AppHeader.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script setup lang="ts">
import DocusHeader from 'docus/app/components/app/AppHeader.vue'
</script>

<template>
<UBanner
id="vitehub-env-nuxt-5"
icon="i-ph-arrow-circle-up-right"
title="On Nuxt 5? Move to @vite-hub/env with one command."
to="/guide/migrate-to-vitehub-env"
:actions="[{ label: 'Migration guide', to: '/guide/migrate-to-vitehub-env', color: 'neutral', variant: 'outline', trailingIcon: 'i-ph-arrow-right' }]"
close
/>
<DocusHeader />
</template>
2 changes: 2 additions & 0 deletions docs/content/1.guide/1.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,6 @@ Each app uses one of the two.

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.

The `.env.example` source needs Node.js 22 or later during `nuxt prepare` and `nuxt build`.
147 changes: 147 additions & 0 deletions docs/content/1.guide/9.migrate-to-vitehub-env.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
---
title: Migrate to ViteHub Env
description: On Nuxt 5, move from this module to @vite-hub/env with one command.
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:

- **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 `<redacted>` 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.

## 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.

::steps

### Preview the changes

```bash
npx @vite-hub/codemods nuxt-safe-runtime-config --dry-run
```

`--dry-run` prints the diff of every file and a report, and writes nothing.

### Apply them

```bash
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
pnpm install
Comment thread
vite-hub[bot] marked this conversation as resolved.
Resolved
npx nuxi prepare
```

Then type-check the app and work through the follow-ups in the report.

::

## What it 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`.

### With `envSchema`

The `.env.example` stays as it is. `prefix: 'NUXT_'` keeps the same variable names and the same `public` split.

```ts [nuxt.config.ts]
import { envSchema } from '@vite-hub/env/vite'

export default defineNuxtConfig({
modules: ['vite-hub/nuxt'],
vitehub: {
preset: 'node',
env: envSchema(new URL('./.env.example', import.meta.url), { prefix: 'NUXT_' }),
},
})
```

### With `$schema`

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.

::code-group

```ts [Before]
export default defineNuxtConfig({
modules: ['nuxt-safe-runtime-config'],
runtimeConfig: {
apiSecret: '',
maxRetries: 3,
featureEnabled: false,
public: { apiBase: 'https://api.example.com' },
},
safeRuntimeConfig: {
$schema: v.object({
apiSecret: v.pipe(v.string(), v.minLength(16)),
maxRetries: v.number(),
featureEnabled: v.boolean(),
public: v.object({ apiBase: v.pipe(v.string(), v.url()) }),
}),
validateAtRuntime: true,
},
})
```

```ts [After]
import { env } from 'vite-hub/env'

export default defineNuxtConfig({
modules: ['vite-hub/nuxt'],
vitehub: {
preset: 'node',
env: {
public: {
apiBase: env({ default: 'https://api.example.com', mode: 'build', source: env.source('NUXT_PUBLIC_API_BASE') }),
},
server: {
apiSecret: env({ secret: true, source: env.source('NUXT_API_SECRET') }),
maxRetries: env.number({ default: 3, source: env.source('NUXT_MAX_RETRIES') }),
featureEnabled: env.boolean({ default: false, source: env.source('NUXT_FEATURE_ENABLED') }),
},
},
},
})
```

::

Server fields with credential-like names (`secret`, `token`, `password`, `key`, database URLs) become `secret: true`.

### In your code

```ts [server/api/config.get.ts]
// Before
const config = useSafeRuntimeConfig(event)

// After
import { useServerEnv } from '#vitehub/env/server'
const config = useServerEnv(event)
```

In app code, `useSafeRuntimeConfig()` becomes `usePublicEnv()` from `#vitehub/env/public`, and `config.public.apiBase` becomes `config.apiBase`.

## Follow-ups

The report lists each change the codemod could not make, with `file:line`:

- **Secret reads.** `config.apiSecret` is now a `SecretEnv<string>`. 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.

::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.
::

Shelve and the [standalone Nitro module](/guide/nitro) are not part of the codemod.
12 changes: 12 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/// <reference types="@nuxt/nitro-server/augments" />
import type { Nuxt } from '@nuxt/schema'
import type { ModuleOptions } from './types'
import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
Expand All @@ -15,6 +16,15 @@ export type { ErrorBehavior, ModuleOptions, SchemaSource, ValidationOptions } fr

const logger = useLogger('safe-runtime-config')

function recommendViteHubEnv(nuxt: Nuxt): void {
if (Number.parseInt(getNuxtVersion(nuxt), 10) < 5)
return
logger.warn([
'On Nuxt 5, use @vite-hub/env instead: it reads the same .env.example, keeps secrets sealed, and also works in Vite and Nitro.',
'Migrate with `npx @vite-hub/codemods nuxt-safe-runtime-config`. Guide: https://nuxt-safe-runtime-config.onmax.me/guide/migrate-to-vitehub-env',
].join('\n'))
}

function applyEnvSchemaDefaults(config: Record<string, unknown>, defaults: Record<string, unknown>): void {
for (const [key, value] of Object.entries(defaults)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
Expand Down Expand Up @@ -50,6 +60,8 @@ export default defineNuxtModule<ModuleOptions>({
jsonSchemaTarget: 'draft-2020-12',
onError: 'throw',
},
onInstall: recommendViteHubEnv,
onUpgrade: recommendViteHubEnv,
async setup(options, nuxt) {
const resolver = createResolver(import.meta.url)
const nuxtMajorVersion = Number.parseInt(getNuxtVersion(nuxt), 10)
Expand Down
32 changes: 32 additions & 0 deletions test/vitehub-env-recommendation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Nuxt } from '@nuxt/schema'
import { describe, expect, it, vi } from 'vitest'

const warn = vi.hoisted(() => vi.fn())
vi.mock('@nuxt/kit', async importOriginal => ({
...await importOriginal<typeof import('@nuxt/kit')>(),
useLogger: () => ({ warn, error: vi.fn(), info: vi.fn(), success: vi.fn() }),
}))

const { default: module } = await import('../src/module')

function nuxtWithVersion(version: string): Nuxt {
return { _version: version, options: {} } as unknown as Nuxt
}

describe('viteHub Env recommendation', () => {
it('stays quiet on Nuxt 4', async () => {
warn.mockClear()
await module.onInstall?.(nuxtWithVersion('4.5.0'))
expect(warn).not.toHaveBeenCalled()
})

it('names the codemod on Nuxt 5 install and upgrade', async () => {
warn.mockClear()
await module.onInstall?.(nuxtWithVersion('5.0.0'))
await module.onUpgrade?.(nuxtWithVersion('5.0.0'), {}, '0.3.2')
expect(warn).toHaveBeenCalledTimes(2)
const message = String(warn.mock.calls[0]![0])
expect(message.split('\n')).toHaveLength(2)
expect(message).toContain('npx @vite-hub/codemods nuxt-safe-runtime-config')
})
})
Loading