npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

get-next-env

v0.1.0

Published

Type-safe runtime environment variables for Next.js. Build once, deploy everywhere.

Readme

get-next-env

npm version bundle size CI Status license npm downloads

Type-safe runtime environment variables for Next.js. Build once, deploy everywhere.


The Problem

Next.js inlines environment variables (like NEXT_PUBLIC_*) at build time into client JavaScript bundles. This breaks the standard "build once, deploy many" pattern required for containerized applications in Docker or Kubernetes, forcing you to rebuild the container for every environment (dev, staging, prod). Existing workarounds often risk leaking server secrets during SSR or break React 19 / CSP nonces.

The Solution

get-next-env injects filtered environment variables at request time directly into page HTML. One Docker image artifact can be built once and deployed across all environments safely and seamlessly.

import { createEnv } from 'get-next-env';

export const env = createEnv({
  GOOGLEMAP_API_KEY: 'GOOGLEMAP_API_KEY',
  ENVIRONMENT: { env: 'NEXT_PUBLIC_ENVIRONMENT', default: 'local' },
});

Installation

npm install get-next-env
# or
pnpm add get-next-env
# or
yarn add get-next-env

Usage

1. App Router (app/layout.tsx)

Inside <head>:

import { EnvScript } from 'get-next-env';
import { env } from '../env.config';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <EnvScript env={env} />
      </head>
      <body>{children}</body>
    </html>
  );
}

2. Pages Router (pages/_document.tsx)

Inside <Head>:

import { Head, Html, Main, NextScript } from 'next/document';
import { EnvScript } from 'get-next-env';
import { env } from '../env.config';

export default function Document() {
  return (
    <Html>
      <Head>
        <EnvScript env={env} />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

3. Usage Modes

Mode 1: Without Validator (Zero Dependencies)

import { createEnv } from 'get-next-env';

export const env = createEnv({
  GOOGLEMAP_API_KEY: 'GOOGLEMAP_API_KEY',
  ENVIRONMENT: { env: 'NEXT_PUBLIC_ENVIRONMENT', default: 'local' },
});

Mode 2: With Zod (Standard Schema)

import { createEnv } from 'get-next-env';
import { z } from 'zod';

export const env = createEnv({
  GOOGLEMAP_API_KEY: { env: 'GOOGLEMAP_API_KEY', schema: z.string().startsWith('AIza') },
  ENVIRONMENT: { env: 'NEXT_PUBLIC_ENVIRONMENT', schema: z.enum(['local', 'dev', 'staging', 'prod']), default: 'local' },
});

Mode 3: With Valibot or Standard Schema Compliant Validator

import { createEnv } from 'get-next-env';
import * as v from 'valibot';

export const env = createEnv({
  GOOGLEMAP_API_KEY: { env: 'GOOGLEMAP_API_KEY', schema: v.pipe(v.string(), v.startsWith('AIza')) },
});

Accessing Variables Anywhere

import { env } from '../env.config';

const apiKey = env.get('GOOGLEMAP_API_KEY');

Startup Validation (Optional)

Call validate() during application initialization or server startup to ensure required variables are present:

env.validate();
// Throws: [get-next-env] Missing "GOOGLEMAP_API_KEY" (process.env.GOOGLEMAP_API_KEY)

API Reference

createEnv(config)

Factory function to define allowed environment variables.

  • Returns: Object with .get(key), .validate(), and .__serialize().

<EnvScript env={env} nonce={nonce} />

React component that injects window.__NEXTENV into the page HTML via a plain <script> element.

  • Props:
    • env: Instance returned by createEnv.
    • nonce (optional): Content Security Policy (CSP) nonce string.

env.validate()

Validates that required environment variables exist and conform to their schemas. Supports three validator interfaces (checked in order):

  1. Standard Schema (~standard property) — Zod ≥3.24, Valibot, ArkType
  2. safeParse() — Zod (all versions)
  3. parse() — Any validator with a parse method

If no schema is provided, validate() only checks that required variables are present.


Security Model

  1. Strict Allowlist Filtering: .get() never reads raw process.env dynamically; it only accesses the pre-built allowlist cache.
  2. SSR Secret Leak Prevention: During SSR, non-allowlisted server secrets in process.env are never accessible or serialized.
  3. XSS Protection: safeSerialize encodes HTML breakout sequences (<, >, &) and Unicode line separators (\u2028, \u2029).
  4. Prototype Pollution Protection: Internal cache is instantiated using Object.create(null).
  5. CSP Nonce Support: Compatible with custom CSP nonces and includes suppressHydrationWarning.

Important: Only include variables in your createEnv config that you are comfortable exposing to the browser.


Why Not Alternatives?

| Feature | get-next-env | next-runtime-env | @t3-oss/env-nextjs | next-public-env | | --- | --- | --- | --- | --- | | Runtime injection | ✅ | ✅ | ❌ (build-time) | ✅ | | Pages Router | ✅ | ❌ (dropped) | ✅ | ❌ | | App Router | ✅ | ✅ | ✅ | ✅ | | Standalone output | ✅ | ❌ | N/A | Unknown | | SSR leak prevention | ✅ | ❌ | N/A | ❌ | | CSP nonce (no hydration error) | ✅ | ❌ | N/A | ❌ | | Next.js 16 / React 19 | ✅ | ❌ | ✅ | ❌ | | Validator-agnostic | ✅ (Standard Schema) | N/A | ❌ (Zod only→Standard Schema) | ❌ (Zod required) | | Works without validator | ✅ | ✅ | ❌ | ❌ | | Zero dependencies | ✅ | ✅ | ❌ | ❌ (Zod) | | Client bundle size | <300 bytes | ~5KB | ~2KB | ~275 bytes |


Edge Runtime

Edge Runtime support has not been fully verified. Please open an issue on GitHub if you need Edge Runtime support or encounter issues.


Contributing

Contributions are welcome! Please check out CONTRIBUTING.md to get started.


License

MIT © Manish Thomas