diff --git a/.github/workflows/pkg.yml b/.github/workflows/pkg.yml index 23eaada..2463084 100644 --- a/.github/workflows/pkg.yml +++ b/.github/workflows/pkg.yml @@ -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 diff --git a/README.md b/README.md index dfb1af0..d045a00 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,9 @@ Validate Nuxt runtime config with Valibot, Zod, ArkType or

+> [!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 diff --git a/docs/app/components/app/AppHeader.vue b/docs/app/components/app/AppHeader.vue new file mode 100644 index 0000000..b1b7458 --- /dev/null +++ b/docs/app/components/app/AppHeader.vue @@ -0,0 +1,15 @@ + + + diff --git a/docs/content/1.guide/1.index.md b/docs/content/1.guide/1.index.md index cfc32ec..145e612 100644 --- a/docs/content/1.guide/1.index.md +++ b/docs/content/1.guide/1.index.md @@ -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`. diff --git a/docs/content/1.guide/9.migrate-to-vitehub-env.md b/docs/content/1.guide/9.migrate-to-vitehub-env.md new file mode 100644 index 0000000..524cab8 --- /dev/null +++ b/docs/content/1.guide/9.migrate-to-vitehub-env.md @@ -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 `` 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 +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`. 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. diff --git a/src/module.ts b/src/module.ts index 8a68b7d..c150d36 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,4 +1,5 @@ /// +import type { Nuxt } from '@nuxt/schema' import type { ModuleOptions } from './types' import { readFile } from 'node:fs/promises' import { createRequire } from 'node:module' @@ -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, defaults: Record): void { for (const [key, value] of Object.entries(defaults)) { if (value && typeof value === 'object' && !Array.isArray(value)) { @@ -50,6 +60,8 @@ export default defineNuxtModule({ 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) diff --git a/test/vitehub-env-recommendation.test.ts b/test/vitehub-env-recommendation.test.ts new file mode 100644 index 0000000..0f8c7f0 --- /dev/null +++ b/test/vitehub-env-recommendation.test.ts @@ -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(), + 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') + }) +})