0Pricing
TypeScript Academy · Lesson

Env typing and config

Validate and type environment variables; expose safe client vars with NEXT_PUBLIC; centralize config for server and client.

Env typing and config is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Intro

Goal: Centralize validated environment variables and keep types in sync. You will parse process.env with zod, export a typed env object, and expose only NEXT_PUBLIC_* to the client.

  • Runtime validation
  • Server vs client exposure
  • Single source of truth

Schemas & parser

Create separate schemas for server and client. Fail fast on invalid config during boot.

// app/lib/env.ts
import { z } from "zod"

const serverSchema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]),
  DATABASE_URL: z.string().url(),
  API_SECRET: z.string().min(1)
})

const clientSchema = z.object({
  NEXT_PUBLIC_API_BASE: z.string().url()
})

function parseEnv<T extends z.ZodTypeAny>(schema: T, source: Record<string, unknown>) {
  const r = schema.safeParse(source)
  if (!r.success) {
    console.error(r.error.format())
    throw new Error("Invalid environment variables")
  }
  return r.data as z.infer<T>
}

export const serverEnv = parseEnv(serverSchema, process.env)
export const clientEnv = parseEnv(clientSchema, process.env)

Server usage

Server files (route handlers, server components) can access secrets from serverEnv. Never expose them to the client.

// app/api/users/route.ts
import { NextResponse } from "next/server"
import { serverEnv } from "@/app/lib/env"

export async function GET() {
  // Safe to read secrets on the server
  const db = serverEnv.DATABASE_URL
  return NextResponse.json({ ok: true, dbConfigured: Boolean(db) })
}

Client usage

Client components import only clientEnv, which contains NEXT_PUBLIC_* vars. Secrets never ship to the browser.

"use client"
import { clientEnv } from "@/app/lib/env"

export default function ApiBaseNotice() {
  return <small>API base: {clientEnv.NEXT_PUBLIC_API_BASE}</small>
}

Ambient typings

Ambient typings improve DX for process.env, but they do not validate at runtime—keep zod checks.

// env.d.ts (optional hints; runtime validation still required)
/// <reference types="node" />

declare namespace NodeJS {
  interface ProcessEnv {
    NODE_ENV: "development" | "test" | "production"
    DATABASE_URL?: string
    API_SECRET?: string
    NEXT_PUBLIC_API_BASE?: string
  }
}

Best practices

Best practices:

  • Never read secrets in client files.
  • Validate once at startup; crash fast in non-prod to catch issues.
  • Group env access behind a small module for consistency and tests.

Env typing check

Quick check: What is a safe pattern for env typing/exposure?

Recap

Recap: Parse process.env with zod, export typed serverEnv/clientEnv, and rely on NEXT_PUBLIC_* for safe client exposure.

Frequently asked questions

Is the “Env typing and config” lesson free?

Yes — the full text of “Env typing and config” is free to read here on the web, and the TypeScript Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Env typing and config”?

Validate and type environment variables; expose safe client vars with NEXT_PUBLIC; centralize config for server and client. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Env typing and config” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. App Router types; server vs client components
  2. Data fetching & action typing
  3. Env typing and config
← Back to TypeScript Academy