Skip to content

requireEnv() ​

Read a variable the app cannot run without. Returns a string or throws with the variable's name.

Import ​

ts
import { requireEnv } from 'next-dynenv'

Signature ​

ts
function requireEnv(key: string): string

Parameters ​

ParameterTypeDescription
keystringVariable name. In the browser it must start with NEXT_PUBLIC_.

Returns ​

The value, typed string. requireEnv() reads through env(), so it follows the same server and browser rules.

Throws ​

When the value is undefined:

text
Required environment variable 'DATABASE_URL' is not defined.
Please set it in your environment or .env file.

In the browser, once window.__ENV exists, a key without the NEXT_PUBLIC_ prefix throws the env() prefix error first.

Behavior ​

VariableResult
https://api.example.comReturns the value
Set to an empty stringReturns ''
Not setThrows

Only undefined fails. Validate content with envParsers.url() or envParsers.enum() when an empty or malformed value would also break the app.

Examples ​

Route handler ​

ts
// app/api/orders/route.ts
import { requireEnv } from 'next-dynenv'

export async function GET() {
    const res = await fetch(`${requireEnv('NEXT_PUBLIC_API_URL')}/orders`, {
        headers: { Authorization: `Bearer ${requireEnv('API_SECRET_KEY')}` },
    })

    return Response.json(await res.json())
}

Config function ​

ts
// lib/config.ts
import { requireEnv } from 'next-dynenv'

export function getConfig() {
    return {
        apiUrl: requireEnv('NEXT_PUBLIC_API_URL'),
        appName: requireEnv('NEXT_PUBLIC_APP_NAME'),
    }
}

Call it inside functions

Keep requireEnv() out of module scope. next build imports your route modules, so a top-level call throws during the build on any machine that lacks production variables, and building without them is how one image serves every environment.

Client component ​

tsx
'use client'

import { requireEnv } from 'next-dynenv'

export function SupportLink() {
    const appName = requireEnv('NEXT_PUBLIC_APP_NAME')

    return <a href="/support">Contact {appName} support</a>
}

Compared with env() ​

env()requireEnv()
Return typestring | undefinedstring
Missing valueundefined or your defaultThrows
Default valueOptional second argumentNone
Use it forOptional settingsRequired settings

For typed values, the json(), url(), and enum() parsers also throw on missing values unless you pass a default. boolean(), number(), and array() fall back to defaults instead.

Released under the MIT License. Forked from next-runtime-env by Expatfile.tax LLC.