Gathering detailed insights and metrics for next-validenv
Gathering detailed insights and metrics for next-validenv
Gathering detailed insights and metrics for next-validenv
Gathering detailed insights and metrics for next-validenv
npm install next-validenv
Typescript
Module System
Node Version
NPM Version
JavaScript (74.06%)
TypeScript (25.94%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
22 Stars
36 Commits
1 Forks
2 Watchers
1 Branches
1 Contributors
Updated on Jun 23, 2025
Latest Version
1.2.2
Package Id
next-validenv@1.2.2
Unpacked Size
13.25 kB
Size
4.17 kB
File Count
6
NPM Version
6.14.15
Node Version
14.18.2
Published on
Jan 16, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
Typesafe environment variables for Next.js
Created by
1npm install zod next-validenv 2 3yarn add zod next-validenv
1npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript 2 3yarn add --dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript
.eslintrc.json
Append "extends"
with "plugin:@typescript-eslint/recommended"
1{ 2 "extends": ["plugin:@typescript-eslint/recommended"] 3}
env.mjs
Where your server and client schemas live for typesafe environment variables
1//@ts-check 2import { validateEnvironmentVariables } from "next-validenv"; 3import { z } from "zod"; 4 5/** 6 * Specify your server-side environment variables schema here. 7 * This way you can ensure the app isn't built with invalid env vars. 8 */ 9export const serverSchema = z.object({ 10 NODE_ENV: z.enum(["development", "test", "production"]), 11}); 12 13/** 14 * Specify your client-side environment variables schema here. 15 * This way you can ensure the app isn't built with invalid env vars. 16 * To expose them to the client, prefix them with `NEXT_PUBLIC_`. 17 */ 18export const clientSchema = z.object({ 19 // NEXT_PUBLIC_TEST: z.string(), 20}); 21 22export const env = validateEnvironmentVariables(serverSchema, clientSchema);
next.config.js
next.config.mjs
1// @ts-check 2/** 3 * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. 4 * This is especially useful for Docker builds. 5 */ 6!process.env.SKIP_ENV_VALIDATION && (await import("./env.mjs")); 7 8/** @type {import("next").NextConfig} */ 9const config = { 10 reactStrictMode: true, 11}; 12export default config;
env.d.ts
1import { env } from "./env.mjs"; 2 3type EnvType = typeof env; 4 5export {}; 6 7declare global { 8 namespace NodeJS { 9 interface ProcessEnv extends EnvType, NodeJS.ProcessEnv {} 10 } 11}
process.env
and get typesafe environment variables1process.env.NODE_ENV; // Typesafe environment variables
Follow the below guide to manually implement typesafe environment variables in Next.js without installing the Next-ValidEnv library
1npm install zod 2 3yarn add zod
1npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript 2 3yarn add --dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript
.eslintrc.json
Append "extends"
with "plugin:@typescript-eslint/recommended"
1{ 2 "extends": ["plugin:@typescript-eslint/recommended"] 3}
env.mjs
Where your server and client schemas live for typesafe environment variables
1// @ts-check 2import { z } from "zod"; 3 4/** 5 * Specify your server-side environment variables schema here. 6 * This way you can ensure the app isn't built with invalid env vars. 7 */ 8export const serverSchema = z.object({ 9 NODE_ENV: z.enum(["development", "test", "production"]), 10}); 11 12/** 13 * Specify your client-side environment variables schema here. 14 * This way you can ensure the app isn't built with invalid env vars. 15 * To expose them to the client, prefix them with `NEXT_PUBLIC_`. 16 */ 17export const clientSchema = z.object({ 18 // NEXT_PUBLIC_TEST: z.string(), 19}); 20 21/** 22 * -------------------------------- 23 * -------------------------------- 24 * DON'T TOUCH ANYTHING BELOW THIS LINE (UNLESS YOU KNOW WHAT YOU'RE DOING) 25 * -------------------------------- 26 * -------------------------------- 27 */ 28 29// maps through zod schema keys and returns an object with the safeParse values from process.env[key] 30export const mapEnvironmentVariablesToObject = ( 31 /** @type {ReturnType<typeof z.object>} */ schema 32) => { 33 /** @type {{ [key: string]: string | undefined; }} */ 34 let env = {}; 35 36 Object.keys(schema.shape).forEach((key) => (env[key] = process.env[key])); 37 38 return schema.safeParse(env); 39}; 40 41export const formatZodErrors = ( 42 /** @type {import('zod').ZodFormattedError<Map<string,string>,string>} */ errors 43) => 44 Object.entries(errors) 45 .map(([name, value]) => { 46 if (value && "_errors" in value) 47 return `${name}: ${value._errors.join(", ")}\n`; 48 }) 49 .filter(Boolean); 50 51export const formatErrors = (/** @type {(string | undefined)[]} */ errors) => 52 errors.map((name) => `${name}\n`); 53 54/** 55 * @function 56 * @template {ReturnType<typeof z.object>} T 57 * @template {ReturnType<typeof z.object>} K 58 * @param {T} serverSchema 59 * @param {K} clientSchema 60 * @returns {z.infer<T> & z.infer<K>} 61 */ 62export const validateEnvironmentVariables = (serverSchema, clientSchema) => { 63 let serverEnv = mapEnvironmentVariablesToObject(serverSchema); 64 let clientEnv = mapEnvironmentVariablesToObject(clientSchema); 65 66 // holds not set environment variable errors for both client and server 67 /** @type {(string | undefined)[]} */ let invalidEnvErrors = []; 68 69 if (!serverEnv.success) { 70 invalidEnvErrors = [ 71 ...invalidEnvErrors, 72 ...formatZodErrors(serverEnv.error.format()), 73 ]; 74 } 75 76 if (!clientEnv.success) { 77 invalidEnvErrors = [ 78 ...invalidEnvErrors, 79 ...formatZodErrors(clientEnv.error.format()), 80 ]; 81 } 82 83 // if one or more environment variables are not set, throw an error 84 if (!serverEnv.success || !clientEnv.success) { 85 console.error("❌ Invalid environment variables:\n", ...invalidEnvErrors); 86 throw new Error("Invalid environment variables"); 87 } 88 89 // holds server environment variables errors that are exposed to the client 90 /** @type {(string | undefined)[]} */ let exposedServerEnvErrors = []; 91 92 for (let key of Object.keys(serverEnv.data)) { 93 if (key.startsWith("NEXT_PUBLIC_")) { 94 exposedServerEnvErrors = [...exposedServerEnvErrors, key]; 95 } 96 } 97 98 // if one or more server environment variables are exposed to the client, throw an error 99 if (exposedServerEnvErrors.length > 0) { 100 console.error( 101 "❌ You are exposing the following server-side environment variables to the client:\n", 102 ...formatErrors(exposedServerEnvErrors) 103 ); 104 throw new Error( 105 "You are exposing the following server-side environment variables to the client" 106 ); 107 } 108 109 // holds client environment variables errors that are not exposed to the client 110 /** @type {(string | undefined)[]} */ let notExposedClientEnvErrors = []; 111 112 for (let key of Object.keys(clientEnv.data)) { 113 if (!key.startsWith("NEXT_PUBLIC_")) { 114 notExposedClientEnvErrors = [...notExposedClientEnvErrors, key]; 115 } 116 } 117 118 // if one or more client environment variables are not exposed to the client, throw an error 119 if (notExposedClientEnvErrors.length > 0) { 120 console.error( 121 "❌ All client-side environment variables must begin with 'NEXT_PUBLIC_', you are not exposing the following:\n", 122 ...formatErrors(notExposedClientEnvErrors) 123 ); 124 throw new Error( 125 "All client-side environment variables must begin with 'NEXT_PUBLIC_', you are not exposing the following:" 126 ); 127 } 128 129 // return both client and server environment variables 130 return { ...serverEnv.data, ...clientEnv.data }; 131}; 132 133export const env = validateEnvironmentVariables(serverSchema, clientSchema);
next.config.js
next.config.mjs
1// @ts-check 2/** 3 * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. 4 * This is especially useful for Docker builds. 5 */ 6!process.env.SKIP_ENV_VALIDATION && (await import("./env.mjs")); 7 8/** @type {import("next").NextConfig} */ 9const config = { 10 reactStrictMode: true, 11}; 12export default config;
env.d.ts
1import { env } from "./env.mjs"; 2 3type EnvType = typeof env; 4 5export {}; 6 7declare global { 8 namespace NodeJS { 9 interface ProcessEnv extends EnvType, NodeJS.ProcessEnv {} 10 } 11}
process.env
and get typesafe environment variables1process.env.NODE_ENV; // Typesafe environment variables
No vulnerabilities found.
No security vulnerabilities found.