Skip to content

Commit d67e45e

Browse files
committed
Add type safety to environment variables
1 parent edb03e9 commit d67e45e

11 files changed

+129
-31
lines changed

.env.example

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Client
2+
NEXT_PUBLIC_VERCEL_URL="http://localhost:3000"
3+
4+
# Server
5+
NODE_ENV="development"

declarations.d.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import z from 'zod';
2+
import { clientSchema, serverSchema } from '@/env/schema.mjs';
3+
4+
declare module '*.svg' {
5+
import React from 'react';
6+
const SVG: React.VFC<React.SVGProps<SVGSVGElement>>;
7+
export default SVG;
8+
};
9+
10+
type EnvSchemaType = z.infer<typeof clientSchema> & z.infer<typeof serverSchema>;
11+
12+
declare global {
13+
namespace NodeJS {
14+
interface ProcessEnv extends EnvSchemaType {}
15+
}
16+
};

next.config.mjs

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import './src/env/index.mjs';
2+
13
/** @type {import('next').NextConfig} */
24
const nextConfig = {};
35

package.json

+16-15
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,26 @@
33
"version": "0.1.0",
44
"private": true,
55
"scripts": {
6-
"dev": "next dev",
6+
"start:local": "next dev",
7+
"start:build": "next start",
78
"build": "next build",
8-
"start": "next start",
9-
"lint": "next lint"
9+
"lint": "next lint --fix"
1010
},
1111
"dependencies": {
12-
"react": "^18",
13-
"react-dom": "^18",
14-
"next": "14.1.0"
12+
"next": "14.1.0",
13+
"react": "^18.2.0",
14+
"react-dom": "^18.2.0",
15+
"zod": "^3.22.4"
1516
},
1617
"devDependencies": {
17-
"typescript": "^5",
18-
"@types/node": "^20",
19-
"@types/react": "^18",
20-
"@types/react-dom": "^18",
21-
"autoprefixer": "^10.0.1",
22-
"postcss": "^8",
23-
"tailwindcss": "^3.3.0",
24-
"eslint": "^8",
25-
"eslint-config-next": "14.1.0"
18+
"@types/node": "^20.11.5",
19+
"@types/react": "^18.2.48",
20+
"@types/react-dom": "^18.2.18",
21+
"autoprefixer": "^10.4.17",
22+
"eslint": "^8.56.0",
23+
"eslint-config-next": "14.1.0",
24+
"postcss": "^8.4.33",
25+
"tailwindcss": "^3.4.1",
26+
"typescript": "^5.3.3"
2627
}
2728
}

pnpm-lock.yaml

+17-10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/env/client.mjs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { formatErrors } from './format.mjs';
2+
import { clientEnv, clientSchema } from './schema.mjs';
3+
4+
const _clientEnv = clientSchema.safeParse(clientEnv);
5+
6+
if (_clientEnv.success === false) {
7+
console.error('❌ Invalid environment variables:\n', ...formatErrors(_clientEnv.error.format()));
8+
throw new Error('Invalid environment variables');
9+
}
10+
11+
// Validate client-side env are exposed to the client
12+
for (const key of Object.keys(_clientEnv.data)) {
13+
if (!key.startsWith('NEXT_PUBLIC_')) {
14+
console.warn('❌ Invalid public environment variable name:\n', key);
15+
throw new Error('Invalid public environment variable name');
16+
}
17+
}
18+
19+
export const env = _clientEnv.data;

src/env/format.mjs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export const formatErrors = (
2+
/** @type { import('zod').ZodFormattedError<Map<string, string>, string> } */
3+
errors
4+
) =>
5+
Object.entries(errors)
6+
.map(([name, value]) => {
7+
if (value && '_errors' in value) return `${name}: ${value._errors.join(', ')}\n`;
8+
})
9+
.filter(Boolean);

src/env/index.mjs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { env as client } from './client.mjs';
2+
import { env as server } from './server.mjs';
3+
4+
const env = { ...client, ...server };
5+
6+
export default env;

src/env/schema.mjs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { z } from 'zod';
2+
3+
export const serverSchema = z.object({
4+
NODE_ENV: z.enum(['development', 'production']).default('development')
5+
});
6+
7+
export const clientSchema = z.object({
8+
NEXT_PUBLIC_VERCEL_URL: z.string().url()
9+
});
10+
11+
/**
12+
* @type {{ [k in keyof z.infer<typeof clientSchema>]: z.infer<typeof clientSchema>[k] | undefined }}
13+
*/
14+
export const clientEnv = {
15+
NEXT_PUBLIC_VERCEL_URL: process.env.NEXT_PUBLIC_VERCEL_URL
16+
};

src/env/server.mjs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { formatErrors } from './format.mjs';
2+
import { serverSchema } from './schema.mjs';
3+
4+
const _serverEnv = serverSchema.safeParse(process.env);
5+
6+
if (_serverEnv.success === false) {
7+
console.error('❌ Invalid environment variables:\n', ...formatErrors(_serverEnv.error.format()));
8+
throw new Error('Invalid environment variables');
9+
}
10+
11+
// Validate server-side env are not exposed to the client
12+
for (const key of Object.keys(_serverEnv.data)) {
13+
if (key.startsWith('NEXT_PUBLIC_')) {
14+
console.warn('❌ You are exposing a server-side env:\n');
15+
throw new Error('You are exposing a server-side env');
16+
}
17+
}
18+
19+
export const env = _serverEnv.data;

tsconfig.json

+4-6
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,13 @@
1212
"isolatedModules": true,
1313
"jsx": "preserve",
1414
"incremental": true,
15-
"plugins": [
16-
{
17-
"name": "next"
18-
}
19-
],
15+
"baseUrl": ".",
16+
"plugins": [{ "name": "next" }],
2017
"paths": {
2118
"@/*": ["./src/*"]
2219
}
2320
},
2421
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
25-
"exclude": ["node_modules"]
22+
"exclude": ["node_modules"],
23+
"files": ["declarations.d.ts"]
2624
}

0 commit comments

Comments
 (0)