diff --git a/docs/content/1.guide/2.installation.md b/docs/content/1.guide/2.installation.md index 8946a61..98a13de 100644 --- a/docs/content/1.guide/2.installation.md +++ b/docs/content/1.guide/2.installation.md @@ -163,11 +163,19 @@ export default defineNuxtConfig({ The build skips the empty value, and the server checks the value it actually received when it starts. [Validation](/guide/validation) explains both checks and `requireAtBuild`, for CI that builds with every production value. ::tip -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`: +For an explicit import in app code, use `#imports`: ```ts import { useSafeRuntimeConfig } from '#imports' ``` + +In server code, use the server alias instead: + +```ts [server/utils/config.ts] +import { useSafeRuntimeConfig } from '#safe-runtime-config/server' +``` + +The server alias reads Nitro's runtime config directly. On Nuxt 5, importing from `#imports` in server code activates Nuxt's Nitro v2 compatibility layer and warns `NUXT_B9003`. Server auto-imports already use the server implementation. :: Next, run the [ESLint rule](/guide/eslint) to find the `useRuntimeConfig()` calls that are still untyped. diff --git a/docs/content/2.reference/1.configuration.md b/docs/content/2.reference/1.configuration.md index 2f0d807..d41b2d7 100644 --- a/docs/content/2.reference/1.configuration.md +++ b/docs/content/2.reference/1.configuration.md @@ -35,7 +35,7 @@ When a library has no JSON Schema output of its own, the module converts it with 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). +Auto-imported in the app and in `server/`. For explicit imports, use `#imports` in app code and `#safe-runtime-config/server` in server code. Without an event it returns the current runtime 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 diff --git a/src/module.ts b/src/module.ts index 9c18461..ceaa77c 100644 --- a/src/module.ts +++ b/src/module.ts @@ -126,10 +126,12 @@ export default defineNuxtModule({ getContents: () => artifacts.typeDeclaration, }) + const serverComposable = resolver.resolve('./runtime/server/useSafeRuntimeConfig') nuxt.hook('nitro:config', (nitroConfig) => { ;(nitroConfig as typeof nitroConfig & { safeRuntimeConfig: typeof validationOptions }).safeRuntimeConfig = validationOptions nitroConfig.alias ||= {} nitroConfig.alias['#safe-runtime-config/nitro-runtime-config'] = runtimeConfigImport + nitroConfig.alias['#safe-runtime-config/server'] = serverComposable nitroConfig.modules ||= [] pushUnique(nitroConfig.modules, safeRuntimeConfigNitroModule) @@ -139,12 +141,8 @@ export default defineNuxtModule({ pushUnique(nitroConfig.typescript.tsConfig.include, './types/safe-runtime-config.d.ts') }) - const composable = { - name: 'useSafeRuntimeConfig', - from: resolver.resolve('./runtime/composables/useSafeRuntimeConfig'), - } - addImports(composable) - addServerImports(composable) + addImports({ name: 'useSafeRuntimeConfig', from: resolver.resolve('./runtime/composables/useSafeRuntimeConfig') }) + addServerImports({ name: 'useSafeRuntimeConfig', from: serverComposable }) nuxt.hook('eslint:config:addons' as any, (addons: Array<{ name: string, getConfigs: () => unknown }>) => { addons.push({ diff --git a/src/runtime/composables/useSafeRuntimeConfig.ts b/src/runtime/composables/useSafeRuntimeConfig.ts index 4b4c736..c2117f8 100644 --- a/src/runtime/composables/useSafeRuntimeConfig.ts +++ b/src/runtime/composables/useSafeRuntimeConfig.ts @@ -1,5 +1,5 @@ import { useRuntimeConfig } from '#imports' -import { ensureRuntimeConfigValidation, useValidatedRuntimeConfig } from '../config-state' +import { readValidatedRuntimeConfig } from '../config-state' declare global { interface NuxtSafeRuntimeConfig {} @@ -14,26 +14,13 @@ export interface SafeRuntimeConfigEvent { * Returns the runtime config with auto-generated type safety. * Types are automatically inferred from your schema defined in nuxt.config.ts. * - * Pass the request event in server handlers to read the event-scoped config, - * the validated equivalent of `useRuntimeConfig(event)`. - * * @example * ```ts - * // Types are auto-generated - no generic needed! * const config = useSafeRuntimeConfig() - * config.secretKey // typed as string * config.public.apiBase // typed as string - * - * export default defineEventHandler((event) => { - * const { secretKey } = useSafeRuntimeConfig(event) - * }) * ``` */ export function useSafeRuntimeConfig(event?: SafeRuntimeConfigEvent): NuxtSafeRuntimeConfig { // The structural event type matches the h3 version Nuxt or Nitro resolves. - const config = useRuntimeConfig(event as Parameters[0]) - // Event configs, including Nuxt's server-side `$config`, validate on first read. - // Asynchronous schemas were already awaited by the validation middleware. - void ensureRuntimeConfigValidation(config) - return useValidatedRuntimeConfig(config) as NuxtSafeRuntimeConfig + return readValidatedRuntimeConfig(useRuntimeConfig(event as Parameters[0])) as NuxtSafeRuntimeConfig } diff --git a/src/runtime/config-state.ts b/src/runtime/config-state.ts index 1f33b3a..8de4fcb 100644 --- a/src/runtime/config-state.ts +++ b/src/runtime/config-state.ts @@ -134,6 +134,16 @@ export function ensureRuntimeConfigValidation(config: RuntimeConfig, environment return validatedState?.status === 'pending' ? validatedState.ready : undefined } +/** + * The validated values of `config`, for `useSafeRuntimeConfig()`. Event configs, including Nuxt's + * server-side `$config`, validate on first read. Asynchronous schemas were already awaited by the + * validation middleware. + */ +export function readValidatedRuntimeConfig(config: RuntimeConfig): RuntimeConfig { + void ensureRuntimeConfigValidation(config) + return useValidatedRuntimeConfig(config) +} + export async function waitForRuntimeConfigValidation(config: RuntimeConfig, environment?: RuntimeConfigEnvironment): Promise { await ensureRuntimeConfigValidation(config, environment) diff --git a/src/runtime/server/useSafeRuntimeConfig.ts b/src/runtime/server/useSafeRuntimeConfig.ts new file mode 100644 index 0000000..1313594 --- /dev/null +++ b/src/runtime/server/useSafeRuntimeConfig.ts @@ -0,0 +1,20 @@ +/// +// Reads Nitro's runtime config directly. Importing `#imports` on the server makes Nuxt 5 apply its Nitro v2 compatibility layer. +import type { SafeRuntimeConfigEvent } from '../composables/useSafeRuntimeConfig' +import { useRuntimeConfig } from '#safe-runtime-config/nitro-runtime-config' +import { readValidatedRuntimeConfig } from '../config-state' + +/** + * Returns the validated runtime config, typed from your schema. + * Pass the request event to read the event-scoped config, the validated equivalent of `useRuntimeConfig(event)`. + * + * @example + * ```ts + * export default defineEventHandler((event) => { + * const { secretKey } = useSafeRuntimeConfig(event) + * }) + * ``` + */ +export function useSafeRuntimeConfig(event?: SafeRuntimeConfigEvent): NuxtSafeRuntimeConfig { + return readValidatedRuntimeConfig(useRuntimeConfig(event)) as NuxtSafeRuntimeConfig +} diff --git a/test/fixtures/runtime-coercion/server/api/config.get.ts b/test/fixtures/runtime-coercion/server/api/config.get.ts index dcb992e..7bf7f54 100644 --- a/test/fixtures/runtime-coercion/server/api/config.get.ts +++ b/test/fixtures/runtime-coercion/server/api/config.get.ts @@ -1,5 +1,7 @@ +import { useSafeRuntimeConfig as useExplicitSafeRuntimeConfig } from '#safe-runtime-config/server' + export default defineEventHandler((event) => { - const config = useSafeRuntimeConfig(event) + const config = useExplicitSafeRuntimeConfig(event) return { secret: config.secret, diff --git a/test/fixtures/server-typing/server/utils/config.ts b/test/fixtures/server-typing/server/utils/config.ts index 6c4cbe3..c6b3bab 100644 --- a/test/fixtures/server-typing/server/utils/config.ts +++ b/test/fixtures/server-typing/server/utils/config.ts @@ -1,9 +1,14 @@ +import { useSafeRuntimeConfig as useExplicitSafeRuntimeConfig } from '#safe-runtime-config/server' + export function getTypedServerConfig(): { secretKey: string, apiBase: string } { const config = useSafeRuntimeConfig() + const explicitConfig = useExplicitSafeRuntimeConfig() // @ts-expect-error unknown keys must be rejected to catch typos type _InvalidKey = typeof config.notARealConfigKey + // @ts-expect-error explicit server imports must reject unknown keys too + type _InvalidExplicitKey = typeof explicitConfig.notARealConfigKey - const secretKey: string = config.secretKey + const secretKey: string = explicitConfig.secretKey const apiBase: string = config.public.apiBase return {