@ryankshaw/next-runtime-env
Version:
Next.js Runtime Environment Configuration - Populates your environment at runtime rather than build time.
22 lines • 1.08 kB
JavaScript
import { isBrowser } from '../helpers/is-browser.js';
import { startsWithNextPublic, } from '../helpers/next-public-utils.js';
import { PUBLIC_ENV_KEY } from './constants.js';
/**
* Reads a safe environment variable (from `window.__ENV` in the browser or `process.env` on the server).
*
* @param key - The environment variable key to read. Must start with 'NEXT_PUBLIC_'
* @returns The environment variable value.
* @throws An error if the environment variable doesn't start with 'NEXT_PUBLIC_' of it is not found
* @example const API_URL = env('NEXT_PUBLIC_API_URL')
*/
export function env(key) {
if (!startsWithNextPublic(key)) {
throw new Error(`Environment variable '${key}' is not public and cannot be accessed using @ryankshaw/next-runtime-env`);
}
const value = isBrowser() ? window[PUBLIC_ENV_KEY]?.[key] : process.env[key];
if (!value) {
throw new Error(`Environment variable '${key}' was not found. Things using @ryankshaw/next-runtime-env are expected to be in process.env`);
}
return value;
}
//# sourceMappingURL=env.js.map