next-runtime-env is a crucial utility for Next.js applications, enabling the dynamic injection of environment variables at runtime rather than solely at build time. This capability is fundamental for adhering to the "build once, deploy many" philosophy, a cornerstone of continuous delivery and the twelve-factor methodology, which Next.js often lacks native support for in frontend contexts. The library allows developers to use the same build artifact across various environments, such as development, staging, and production, without the need for environment-specific rebuilds. The current stable version is `3.3.0`, with recent alpha and stable releases indicating active maintenance. It offers isomorphic design, ensuring seamless operation across server, browser, and middleware environments. Key differentiators include full compatibility with Next.js 13 and 14, and native support for `.env` files during development. The package maintains distinct major versions (1.x, 2.x, 3.x) to align with specific Next.js router types and major versions, providing tailored solutions for the Pages Router (1.x), Next.js 13 App Router (2.x), and Next.js 14 with enhanced caching (3.x).
npm install next-runtime-envVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to configure `next-runtime-env` for a Next.js App Router project (v3.x), placing `PublicEnvScript` in `app/layout.tsx` to expose environment variables and then accessing them in a client component using the `env` function.
Consult the `next-runtime-env` documentation for the correct version matching your Next.js setup: v1.x for Next.js 12/13 Pages Router, v2.x for Next.js 13 App Router, and v3.x for Next.js 14 App Router with improved caching.
Always use the `env('YOUR_VAR_NAME')` function provided by `next-runtime-env` within client components to correctly access environment variables exposed at runtime. `process.env` is only reliable for server-side or build-time variables.Add `next-runtime-env` to the `experimental.serverComponentsExternalPackages` array in your `next.config.js` to ensure proper functionality and avoid potential issues with server-side rendering and hydration.
For runtime-injected environment variables in client-side code, use `import { env } from 'next-runtime-env';` and then `env('YOUR_VAR_NAME')`.Ensure `PublicEnvScript` is present and correctly placed in the `<head>`. Verify that public variables are prefixed with `NEXT_PUBLIC_`. For non-public variables, follow the documentation on using `makeEnvPublic`.
Check the `next-runtime-env` compatibility guide in its README. For Next.js 12/13 Pages Router, use `next-runtime-env@1.x`. For Next.js 13 App Router, use `next-runtime-env@2.x`. For Next.js 14 App Router, use `next-runtime-env@3.x`.