@matthew-hre/env 0.2.0 → 0.3.1

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,6 +1,6 @@
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
6
 
@@ -10,14 +10,44 @@ Type safe environment variable validation for NextJS projects.
10
10
  npm install @matthew-hre/env
11
11
  ```
12
12
 
13
- ### env.ts
13
+ ## Usage
14
+
15
+ ### Client/Server Schema (Recommended)
14
16
 
15
- First, create an `env.ts` file in your project (e.g. in the `lib` folder):
17
+ For NextJS projects, you can separate client and server environment variables for better security and type safety:
16
18
 
17
19
  ```ts
18
20
  // lib/env.ts
21
+ import { loadEnv } from "@matthew-hre/env";
19
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
20
48
  import { loadEnv } from "@matthew-hre/env";
49
+ // lib/env.ts
50
+ import { z } from "zod";
21
51
 
22
52
  const schema = z.object({
23
53
  NODE_ENV: z.string(),
@@ -32,40 +62,89 @@ export const env = loadEnv(schema);
32
62
 
33
63
  ### next.config.js
34
64
 
35
- Then, import and use the `env` object in your `next.config.js`:
65
+ Import the `env` file in your `next.config.js`. This is enough to ensure the environment variables are validated at build time.
36
66
 
37
- ```js
38
- // next.config.js
67
+ ```ts
68
+ // next.config.ts
39
69
  import type { NextConfig } from "next";
40
- import { env } from "src/lib/env"; // or wherever your env.ts file is
70
+
71
+ import "src/lib/env";
41
72
 
42
73
  const nextConfig: NextConfig = {
43
- ...
74
+ // ...
44
75
  };
45
76
 
46
77
  export default nextConfig;
47
78
  ```
48
79
 
49
- ## Usage
80
+ ## Examples
50
81
 
51
- You can now use the `env` object anywhere in your NextJS project:
82
+ ### Using Client/Server Environment Variables
52
83
 
53
84
  ```ts
54
- import { env } from "src/lib/env"; // or wherever your env.ts file is
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";
55
103
 
56
- console.log(env.NEXT_PUBLIC_API_URL);
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
+ }
57
117
  ```
58
118
 
59
- This is type safe and will give you autocompletion based on your schema. Additionally, errors will be thrown at runtime if the environment variables do not match the schema.
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
+ ```
60
132
 
61
133
  ## Configuration
62
134
 
63
- The `loadEnv` function accepts two optional parameters: `env` and `options`.
135
+ The `loadEnv` function accepts optional parameters:
64
136
 
65
137
  - `env`: An object representing the environment variables to validate. Defaults to `process.env`.
66
- - `options`: An object containing options to customize the behavior of the `loadEnv` function.
138
+ - `options`: An object containing options to customize the behavior:
67
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`.
68
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
+
69
148
  ## License
70
149
 
71
150
  Matthew Hrehirchuk © 2025. Licensed under the MIT License.
package/dist/index.cjs CHANGED
@@ -36,22 +36,96 @@ module.exports = __toCommonJS(index_exports);
36
36
 
37
37
  // src/core/load-env.ts
38
38
  var import_zod = require("zod");
39
+
40
+ // src/core/error-handling.ts
39
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
40
71
  var defaultOptions = {
41
72
  exitOnError: true
42
73
  };
43
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
+ const isServer = typeof window === "undefined";
89
+ if (isServer) {
90
+ try {
91
+ serverEnv = schema.server.parse(env);
92
+ } catch (err) {
93
+ if (err instanceof import_zod.ZodError) {
94
+ errors.push({ context: "server", error: err });
95
+ } else {
96
+ throw err;
97
+ }
98
+ }
99
+ } else {
100
+ serverEnv = new Proxy({}, {
101
+ get: () => {
102
+ throw new Error("\u274C Attempted to access a server-side environment variable on the client");
103
+ }
104
+ });
105
+ }
106
+ const clientEnv_variables = Object.fromEntries(
107
+ Object.entries(env).filter(([key]) => key.startsWith("NEXT_PUBLIC_"))
108
+ );
109
+ try {
110
+ clientEnv = schema.client.parse(clientEnv_variables);
111
+ } catch (err) {
112
+ if (err instanceof import_zod.ZodError) {
113
+ errors.push({ context: "client", error: err });
114
+ } else {
115
+ throw err;
116
+ }
117
+ }
118
+ if (errors.length > 0) {
119
+ handleClientServerErrors(errors, options);
120
+ }
121
+ return { serverEnv, clientEnv };
122
+ }
123
+ function parseSingleSchema(schema, env, options) {
44
124
  try {
45
125
  return schema.parse(env);
46
126
  } catch (err) {
47
127
  if (err instanceof import_zod.ZodError) {
48
- let message = import_picocolors.default.red("Invalid environment variables:\n");
49
- err.issues.forEach((issue) => {
50
- const name = String(issue.path[0]);
51
- message += ` - ${import_picocolors.default.bold(name)} ${import_picocolors.default.dim("(" + issue.message + ")")}
52
- `;
53
- });
54
- console.error(message);
128
+ handleSingleSchemaError(err);
55
129
  } else {
56
130
  console.error("Unexpected error while parsing env:", err);
57
131
  }
package/dist/index.d.cts CHANGED
@@ -1,8 +1,22 @@
1
- import { ZodRawShape, ZodObject, z } from 'zod';
1
+ import { ZodObject, z, ZodRawShape } from 'zod';
2
2
 
3
- interface LoadEnvOptions {
3
+ type LoadEnvOptions = {
4
4
  exitOnError?: boolean;
5
- }
6
- declare function loadEnv<T extends ZodRawShape>(schema: ZodObject<T>, env?: Record<string, string | undefined>, options?: LoadEnvOptions): z.output<typeof schema>;
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;
7
18
 
8
- 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,8 +1,22 @@
1
- import { ZodRawShape, ZodObject, z } from 'zod';
1
+ import { ZodObject, z, ZodRawShape } from 'zod';
2
2
 
3
- interface LoadEnvOptions {
3
+ type LoadEnvOptions = {
4
4
  exitOnError?: boolean;
5
- }
6
- declare function loadEnv<T extends ZodRawShape>(schema: ZodObject<T>, env?: Record<string, string | undefined>, options?: LoadEnvOptions): z.output<typeof schema>;
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;
7
18
 
8
- 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,21 +1,95 @@
1
1
  // src/core/load-env.ts
2
- import { ZodError } from "zod";
2
+ import { ZodError, ZodObject } from "zod";
3
+
4
+ // src/core/error-handling.ts
3
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
4
35
  var defaultOptions = {
5
36
  exitOnError: true
6
37
  };
7
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
+ const isServer = typeof window === "undefined";
53
+ if (isServer) {
54
+ try {
55
+ serverEnv = schema.server.parse(env);
56
+ } catch (err) {
57
+ if (err instanceof ZodError) {
58
+ errors.push({ context: "server", error: err });
59
+ } else {
60
+ throw err;
61
+ }
62
+ }
63
+ } else {
64
+ serverEnv = new Proxy({}, {
65
+ get: () => {
66
+ throw new Error("\u274C Attempted to access a server-side environment variable on the client");
67
+ }
68
+ });
69
+ }
70
+ const clientEnv_variables = Object.fromEntries(
71
+ Object.entries(env).filter(([key]) => key.startsWith("NEXT_PUBLIC_"))
72
+ );
73
+ try {
74
+ clientEnv = schema.client.parse(clientEnv_variables);
75
+ } catch (err) {
76
+ if (err instanceof ZodError) {
77
+ errors.push({ context: "client", error: err });
78
+ } else {
79
+ throw err;
80
+ }
81
+ }
82
+ if (errors.length > 0) {
83
+ handleClientServerErrors(errors, options);
84
+ }
85
+ return { serverEnv, clientEnv };
86
+ }
87
+ function parseSingleSchema(schema, env, options) {
8
88
  try {
9
89
  return schema.parse(env);
10
90
  } catch (err) {
11
91
  if (err instanceof ZodError) {
12
- let message = pc.red("Invalid environment variables:\n");
13
- err.issues.forEach((issue) => {
14
- const name = String(issue.path[0]);
15
- message += ` - ${pc.bold(name)} ${pc.dim("(" + issue.message + ")")}
16
- `;
17
- });
18
- console.error(message);
92
+ handleSingleSchemaError(err);
19
93
  } else {
20
94
  console.error("Unexpected error while parsing env:", err);
21
95
  }
package/package.json CHANGED
@@ -1,8 +1,17 @@
1
1
  {
2
2
  "name": "@matthew-hre/env",
3
- "version": "0.2.0",
4
- "description": "Type safe environment variable validation for NextJS projects",
5
3
  "type": "module",
4
+ "version": "0.3.1",
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": [
@@ -11,28 +20,28 @@
11
20
  "scripts": {
12
21
  "build": "tsup src/index.ts --format esm,cjs --dts",
13
22
  "dev": "tsup src/index.ts --watch --dts",
14
- "test": "vitest"
23
+ "test": "vitest",
24
+ "lint": "eslint .",
25
+ "lint:fix": "eslint ."
15
26
  },
16
- "keywords": [
17
- "nextjs",
18
- "zod",
19
- "env",
20
- "typed",
21
- "validation"
22
- ],
23
- "author": "Matthew Hrehirchuk",
24
- "license": "MIT",
25
27
  "dependencies": {
26
28
  "picocolors": "^1.1.1",
27
29
  "zod": "^4.1.9"
28
30
  },
29
31
  "devDependencies": {
32
+ "@antfu/eslint-config": "^5.4.1",
33
+ "@eslint/js": "^9.36.0",
30
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",
31
39
  "tsup": "^8.5.0",
32
40
  "typescript": "^5.9.2",
41
+ "typescript-eslint": "^8.44.0",
33
42
  "vitest": "^3.2.4"
34
43
  },
35
44
  "publishConfig": {
36
45
  "access": "public"
37
46
  }
38
- }
47
+ }