@matthew-hre/env 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,150 @@
1
1
  # @matthew-hre/env
2
2
 
3
- Type safe environment variable validation for NextJS projects.
3
+ Type safe environment variable validation for NextJS projects with support for client/server separation.
4
4
 
5
5
  > This package is mostly for my own projects, and I wouldn't recommend using it yourself in its current state. It may be improved in the future. May.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @matthew-hre/env
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Client/Server Schema (Recommended)
16
+
17
+ For NextJS projects, you can separate client and server environment variables for better security and type safety:
18
+
19
+ ```ts
20
+ // lib/env.ts
21
+ import { loadEnv } from "@matthew-hre/env";
22
+ import { z } from "zod";
23
+
24
+ const schema = {
25
+ server: z.object({
26
+ NODE_ENV: z.enum(["development", "production"]),
27
+ DATABASE_URL: z.string().url(),
28
+ SECRET_KEY: z.string(),
29
+ }),
30
+ client: z.object({
31
+ NEXT_PUBLIC_API_URL: z.string().url(),
32
+ NEXT_PUBLIC_APP_NAME: z.string(),
33
+ }),
34
+ };
35
+
36
+ // optionally, export the schemas for use elsewhere
37
+ export type ServerEnvSchema = z.infer<typeof schema.server>;
38
+ export type ClientEnvSchema = z.infer<typeof schema.client>;
39
+
40
+ export const { serverEnv, clientEnv } = loadEnv(schema);
41
+ ```
42
+
43
+ ### Legacy Single Schema
44
+
45
+ For simpler projects or backward compatibility, you can still use the original single schema format:
46
+
47
+ ```ts
48
+ import { loadEnv } from "@matthew-hre/env";
49
+ // lib/env.ts
50
+ import { z } from "zod";
51
+
52
+ const schema = z.object({
53
+ NODE_ENV: z.string(),
54
+ NEXT_PUBLIC_API_URL: z.url(),
55
+ });
56
+
57
+ // optionally, export the schema for use elsewhere
58
+ export type EnvSchema = z.infer<typeof schema>;
59
+
60
+ export const env = loadEnv(schema);
61
+ ```
62
+
63
+ ### next.config.js
64
+
65
+ Import the `env` file in your `next.config.js`. This is enough to ensure the environment variables are validated at build time.
66
+
67
+ ```ts
68
+ // next.config.ts
69
+ import type { NextConfig } from "next";
70
+
71
+ import "src/lib/env";
72
+
73
+ const nextConfig: NextConfig = {
74
+ // ...
75
+ };
76
+
77
+ export default nextConfig;
78
+ ```
79
+
80
+ ## Examples
81
+
82
+ ### Using Client/Server Environment Variables
83
+
84
+ ```ts
85
+ // server-side code (api routes, etc.)
86
+ import { clientEnv, serverEnv } from "src/lib/env";
87
+
88
+ export async function GET() {
89
+ // can access both server and client variables
90
+ const dbUrl = serverEnv.DATABASE_URL;
91
+ const apiUrl = clientEnv.NEXT_PUBLIC_API_URL;
92
+
93
+ // full type safety and autocompletion
94
+ return fetch(`${apiUrl}/data`, {
95
+ headers: { authorization: serverEnv.SECRET_KEY }
96
+ });
97
+ }
98
+ ```
99
+
100
+ ```tsx
101
+ // client-side code (components, hooks, etc.)
102
+ "use client";
103
+
104
+ import { clientEnv } from "src/lib/env";
105
+
106
+ export function ApiClient() {
107
+ // can access client variables
108
+ const apiUrl = clientEnv.NEXT_PUBLIC_API_URL;
109
+
110
+ return (
111
+ <span>
112
+ API URL:
113
+ {apiUrl}
114
+ </span>
115
+ );
116
+ }
117
+ ```
118
+
119
+ ### Environment Variable Validation
120
+
121
+ ```ts
122
+ const schema = {
123
+ server: z.object({
124
+ NODE_ENV: z.enum(["development", "production"]),
125
+ DATABASE_URL: z.url(),
126
+ }),
127
+ client: z.object({
128
+ NEXT_PUBLIC_API_URL: z.url(),
129
+ }),
130
+ };
131
+ ```
132
+
133
+ ## Configuration
134
+
135
+ The `loadEnv` function accepts optional parameters:
136
+
137
+ - `env`: An object representing the environment variables to validate. Defaults to `process.env`.
138
+ - `options`: An object containing options to customize the behavior:
139
+ - `exitOnError`: If set to `true`, the process will exit with a non-zero status code if the environment variables are invalid. Defaults to `true`.
140
+
141
+ ```ts
142
+ const customEnv = { NODE_ENV: "test", NEXT_PUBLIC_API_URL: "http://localhost:3000" };
143
+ const { serverEnv, clientEnv } = loadEnv(schema, customEnv);
144
+
145
+ const { serverEnv, clientEnv } = loadEnv(schema, process.env, { exitOnError: false });
146
+ ```
147
+
148
+ ## License
149
+
150
+ Matthew Hrehirchuk © 2025. Licensed under the MIT License.
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -23,22 +33,97 @@ __export(index_exports, {
23
33
  loadEnv: () => loadEnv
24
34
  });
25
35
  module.exports = __toCommonJS(index_exports);
36
+
37
+ // src/core/load-env.ts
26
38
  var import_zod = require("zod");
27
- function loadEnv(schema, env = process.env) {
39
+
40
+ // src/core/error-handling.ts
41
+ var import_picocolors = __toESM(require("picocolors"), 1);
42
+ function handleClientServerErrors(errors, options) {
43
+ let message = import_picocolors.default.red("Invalid environment variables:\n");
44
+ errors.forEach(({ context, error }) => {
45
+ message += import_picocolors.default.yellow(`
46
+ ${context.toUpperCase()} variables:
47
+ `);
48
+ error.issues.forEach((issue) => {
49
+ const name = String(issue.path[0]);
50
+ message += ` - ${import_picocolors.default.bold(name)} ${import_picocolors.default.dim(`(${issue.message})`)}
51
+ `;
52
+ });
53
+ });
54
+ console.error(message);
55
+ if (options.exitOnError) {
56
+ process.exit(1);
57
+ }
58
+ throw errors[0].error;
59
+ }
60
+ function handleSingleSchemaError(error) {
61
+ let message = import_picocolors.default.red("Invalid environment variables:\n");
62
+ error.issues.forEach((issue) => {
63
+ const name = String(issue.path[0]);
64
+ message += ` - ${import_picocolors.default.bold(name)} ${import_picocolors.default.dim(`(${issue.message})`)}
65
+ `;
66
+ });
67
+ console.error(message);
68
+ }
69
+
70
+ // src/core/load-env.ts
71
+ var defaultOptions = {
72
+ exitOnError: true
73
+ };
74
+ function loadEnv(schema, env = process.env, options = defaultOptions) {
75
+ if (isClientServerSchema(schema)) {
76
+ return parseClientServerSchema(schema, env, options);
77
+ } else {
78
+ return parseSingleSchema(schema, env, options);
79
+ }
80
+ }
81
+ function isClientServerSchema(schema) {
82
+ return typeof schema === "object" && schema !== null && "server" in schema && "client" in schema && schema.server instanceof import_zod.ZodObject && schema.client instanceof import_zod.ZodObject;
83
+ }
84
+ function parseClientServerSchema(schema, env, options) {
85
+ const errors = [];
86
+ let serverEnv;
87
+ let clientEnv;
88
+ try {
89
+ serverEnv = schema.server.parse(env);
90
+ } catch (err) {
91
+ if (err instanceof import_zod.ZodError) {
92
+ errors.push({ context: "server", error: err });
93
+ } else {
94
+ throw err;
95
+ }
96
+ }
97
+ const clientEnv_variables = Object.fromEntries(
98
+ Object.entries(env).filter(([key]) => key.startsWith("NEXT_PUBLIC_"))
99
+ );
100
+ try {
101
+ clientEnv = schema.client.parse(clientEnv_variables);
102
+ } catch (err) {
103
+ if (err instanceof import_zod.ZodError) {
104
+ errors.push({ context: "client", error: err });
105
+ } else {
106
+ throw err;
107
+ }
108
+ }
109
+ if (errors.length > 0) {
110
+ handleClientServerErrors(errors, options);
111
+ }
112
+ return { serverEnv, clientEnv };
113
+ }
114
+ function parseSingleSchema(schema, env, options) {
28
115
  try {
29
116
  return schema.parse(env);
30
117
  } catch (err) {
31
118
  if (err instanceof import_zod.ZodError) {
32
- let message = "Invalid environment variables:\n";
33
- err.issues.forEach((issue) => {
34
- message += ` - ${String(issue.path[0])} (${issue.message})
35
- `;
36
- });
37
- console.error(message);
119
+ handleSingleSchemaError(err);
38
120
  } else {
39
121
  console.error("Unexpected error while parsing env:", err);
40
122
  }
41
- process.exit(1);
123
+ if (options.exitOnError) {
124
+ process.exit(1);
125
+ }
126
+ throw err;
42
127
  }
43
128
  }
44
129
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.d.cts CHANGED
@@ -1,5 +1,22 @@
1
- import { ZodRawShape, ZodObject, z } from 'zod';
1
+ import { ZodObject, z, ZodRawShape } from 'zod';
2
2
 
3
- declare function loadEnv<T extends ZodRawShape>(schema: ZodObject<T>, env?: Record<string, string | undefined>): z.output<typeof schema>;
3
+ type LoadEnvOptions = {
4
+ exitOnError?: boolean;
5
+ };
6
+ type ClientServerSchema = {
7
+ server: ZodObject<any>;
8
+ client: ZodObject<any>;
9
+ };
10
+ type IsClientServerSchema<T> = T extends ClientServerSchema ? true : false;
11
+ type LoadEnvResult<T> = IsClientServerSchema<T> extends true ? T extends {
12
+ server: infer S;
13
+ client: infer C;
14
+ } ? S extends ZodObject<any> ? C extends ZodObject<any> ? {
15
+ serverEnv: z.output<S>;
16
+ clientEnv: z.output<C>;
17
+ } : never : never : never : T extends ZodObject<infer R> ? z.output<ZodObject<R>> : never;
4
18
 
5
- export { loadEnv };
19
+ declare function loadEnv<T extends ClientServerSchema>(schema: T, env?: Record<string, string | undefined>, options?: LoadEnvOptions): LoadEnvResult<T>;
20
+ declare function loadEnv<T extends ZodRawShape>(schema: ZodObject<T>, env?: Record<string, string | undefined>, options?: LoadEnvOptions): LoadEnvResult<ZodObject<T>>;
21
+
22
+ export { type ClientServerSchema, type LoadEnvOptions, type LoadEnvResult, loadEnv };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,22 @@
1
- import { ZodRawShape, ZodObject, z } from 'zod';
1
+ import { ZodObject, z, ZodRawShape } from 'zod';
2
2
 
3
- declare function loadEnv<T extends ZodRawShape>(schema: ZodObject<T>, env?: Record<string, string | undefined>): z.output<typeof schema>;
3
+ type LoadEnvOptions = {
4
+ exitOnError?: boolean;
5
+ };
6
+ type ClientServerSchema = {
7
+ server: ZodObject<any>;
8
+ client: ZodObject<any>;
9
+ };
10
+ type IsClientServerSchema<T> = T extends ClientServerSchema ? true : false;
11
+ type LoadEnvResult<T> = IsClientServerSchema<T> extends true ? T extends {
12
+ server: infer S;
13
+ client: infer C;
14
+ } ? S extends ZodObject<any> ? C extends ZodObject<any> ? {
15
+ serverEnv: z.output<S>;
16
+ clientEnv: z.output<C>;
17
+ } : never : never : never : T extends ZodObject<infer R> ? z.output<ZodObject<R>> : never;
4
18
 
5
- export { loadEnv };
19
+ declare function loadEnv<T extends ClientServerSchema>(schema: T, env?: Record<string, string | undefined>, options?: LoadEnvOptions): LoadEnvResult<T>;
20
+ declare function loadEnv<T extends ZodRawShape>(schema: ZodObject<T>, env?: Record<string, string | undefined>, options?: LoadEnvOptions): LoadEnvResult<ZodObject<T>>;
21
+
22
+ export { type ClientServerSchema, type LoadEnvOptions, type LoadEnvResult, loadEnv };
package/dist/index.js CHANGED
@@ -1,20 +1,93 @@
1
- // src/index.ts
2
- import { ZodError } from "zod";
3
- function loadEnv(schema, env = process.env) {
1
+ // src/core/load-env.ts
2
+ import { ZodError, ZodObject } from "zod";
3
+
4
+ // src/core/error-handling.ts
5
+ import pc from "picocolors";
6
+ function handleClientServerErrors(errors, options) {
7
+ let message = pc.red("Invalid environment variables:\n");
8
+ errors.forEach(({ context, error }) => {
9
+ message += pc.yellow(`
10
+ ${context.toUpperCase()} variables:
11
+ `);
12
+ error.issues.forEach((issue) => {
13
+ const name = String(issue.path[0]);
14
+ message += ` - ${pc.bold(name)} ${pc.dim(`(${issue.message})`)}
15
+ `;
16
+ });
17
+ });
18
+ console.error(message);
19
+ if (options.exitOnError) {
20
+ process.exit(1);
21
+ }
22
+ throw errors[0].error;
23
+ }
24
+ function handleSingleSchemaError(error) {
25
+ let message = pc.red("Invalid environment variables:\n");
26
+ error.issues.forEach((issue) => {
27
+ const name = String(issue.path[0]);
28
+ message += ` - ${pc.bold(name)} ${pc.dim(`(${issue.message})`)}
29
+ `;
30
+ });
31
+ console.error(message);
32
+ }
33
+
34
+ // src/core/load-env.ts
35
+ var defaultOptions = {
36
+ exitOnError: true
37
+ };
38
+ function loadEnv(schema, env = process.env, options = defaultOptions) {
39
+ if (isClientServerSchema(schema)) {
40
+ return parseClientServerSchema(schema, env, options);
41
+ } else {
42
+ return parseSingleSchema(schema, env, options);
43
+ }
44
+ }
45
+ function isClientServerSchema(schema) {
46
+ return typeof schema === "object" && schema !== null && "server" in schema && "client" in schema && schema.server instanceof ZodObject && schema.client instanceof ZodObject;
47
+ }
48
+ function parseClientServerSchema(schema, env, options) {
49
+ const errors = [];
50
+ let serverEnv;
51
+ let clientEnv;
52
+ try {
53
+ serverEnv = schema.server.parse(env);
54
+ } catch (err) {
55
+ if (err instanceof ZodError) {
56
+ errors.push({ context: "server", error: err });
57
+ } else {
58
+ throw err;
59
+ }
60
+ }
61
+ const clientEnv_variables = Object.fromEntries(
62
+ Object.entries(env).filter(([key]) => key.startsWith("NEXT_PUBLIC_"))
63
+ );
64
+ try {
65
+ clientEnv = schema.client.parse(clientEnv_variables);
66
+ } catch (err) {
67
+ if (err instanceof ZodError) {
68
+ errors.push({ context: "client", error: err });
69
+ } else {
70
+ throw err;
71
+ }
72
+ }
73
+ if (errors.length > 0) {
74
+ handleClientServerErrors(errors, options);
75
+ }
76
+ return { serverEnv, clientEnv };
77
+ }
78
+ function parseSingleSchema(schema, env, options) {
4
79
  try {
5
80
  return schema.parse(env);
6
81
  } catch (err) {
7
82
  if (err instanceof ZodError) {
8
- let message = "Invalid environment variables:\n";
9
- err.issues.forEach((issue) => {
10
- message += ` - ${String(issue.path[0])} (${issue.message})
11
- `;
12
- });
13
- console.error(message);
83
+ handleSingleSchemaError(err);
14
84
  } else {
15
85
  console.error("Unexpected error while parsing env:", err);
16
86
  }
17
- process.exit(1);
87
+ if (options.exitOnError) {
88
+ process.exit(1);
89
+ }
90
+ throw err;
18
91
  }
19
92
  }
20
93
  export {
package/package.json CHANGED
@@ -1,8 +1,17 @@
1
1
  {
2
2
  "name": "@matthew-hre/env",
3
- "version": "0.1.0",
4
- "description": "Type safe environment variable validation for NextJS projects",
5
3
  "type": "module",
4
+ "version": "0.3.0",
5
+ "description": "Type safe environment variable validation for NextJS projects",
6
+ "author": "Matthew Hrehirchuk",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "nextjs",
10
+ "zod",
11
+ "env",
12
+ "typed",
13
+ "validation"
14
+ ],
6
15
  "main": "./dist/index.js",
7
16
  "types": "./dist/index.d.ts",
8
17
  "files": [
@@ -10,26 +19,29 @@
10
19
  ],
11
20
  "scripts": {
12
21
  "build": "tsup src/index.ts --format esm,cjs --dts",
13
- "dev": "tsup src/index.ts --watch --dts"
22
+ "dev": "tsup src/index.ts --watch --dts",
23
+ "test": "vitest",
24
+ "lint": "eslint .",
25
+ "lint:fix": "eslint ."
14
26
  },
15
- "keywords": [
16
- "nextjs",
17
- "zod",
18
- "env",
19
- "typed",
20
- "validation"
21
- ],
22
- "author": "Matthew Hrehirchuk",
23
- "license": "MIT",
24
27
  "dependencies": {
28
+ "picocolors": "^1.1.1",
25
29
  "zod": "^4.1.9"
26
30
  },
27
31
  "devDependencies": {
32
+ "@antfu/eslint-config": "^5.4.1",
33
+ "@eslint/js": "^9.36.0",
28
34
  "@types/node": "^24.5.2",
35
+ "eslint": "^9.36.0",
36
+ "eslint-plugin-format": "^1.0.2",
37
+ "globals": "^16.4.0",
38
+ "jiti": "^2.5.1",
29
39
  "tsup": "^8.5.0",
30
- "typescript": "^5.9.2"
40
+ "typescript": "^5.9.2",
41
+ "typescript-eslint": "^8.44.0",
42
+ "vitest": "^3.2.4"
31
43
  },
32
44
  "publishConfig": {
33
45
  "access": "public"
34
46
  }
35
- }
47
+ }