Add Environment Variable

VerifiedSafe

Adds a new environment variable with Zod validation. Modify src/env.ts, .env.example, and tests to integrate application configuration.

Sby Skills Guide Bot
DevelopmentBeginner
3/9/2026
Claude CodeCursorWindsurfCodex
#environment-variables#zod#configuration#typescript#validation

Recommended for

Automated summary

Adds a new environment variable with Zod validation in src/env.ts, documents it in .env.example, and extends the validation tests.

Strengths

  • Covers the full chain: Zod schema, mapping object, .env.example documentation and tests
  • Ships ready-made patterns for common cases (optional, default, coerced number, URL, enum, boolean)
  • Enforces importing from @/env instead of reading process.env directly

Limitations

  • Assumes a specific template layout (src/env.ts, getEnv helper, BT_ prefix)
  • Does not address secret storage or propagating the variable to deployed environments
  • Relies entirely on Zod for validation
When to use it

Use it when adding configuration for an external service, a feature flag or an application setting in a TypeScript project built around src/env.ts.

When not to use it

Avoid it on projects that don't use Zod or this env-file structure, or when the task is managing production secrets.

Security analysis

Safe
Quality score84/100

This skill is pure instructional documentation for adding environment variables to a TypeScript/Zod codebase. It declares no tools, executes no commands, touches no network or secrets, and explicitly warns against committing secrets to .env.example. The only files it guides edits to are project-local source, example, and test files, so there is no meaningful execution risk.

No concerns found

How this analysis is made

Examples

Add an API key
Add a new required env variable BT_MY_API_KEY for our payment provider, with Zod validation in src/env.ts, a line in .env.example and the matching tests.
Feature flag
Add an environment variable to enable the new dashboard feature, defaulting to false, and wire it into src/env.ts, .env.example and tests/env.test.ts.
Optional webhook URL
Add an optional BT_WEBHOOK_URL variable validated as a URL and documented in .env.example.

name: add-env-variable description: Add a new environment variable to the application. Use when adding configuration for external services, feature flags, or application settings. Triggers on "add env", "environment variable", "config variable".

Add Environment Variable

Adds a new environment variable with Zod validation. All environment variables must be defined in src/env.ts and documented in .env.example.

Quick Reference

Files to modify:

  1. src/env.ts - Add to schema and mapping
  2. .env.example - Document the variable
  3. tests/env.test.ts - Add validation tests

Instructions

Step 1: Add to Schema in src/env.ts

Add the variable to the envSchema object:

const envSchema = z.object({
  // ... existing variables ...

  // Your new variable (with comment explaining purpose)
  NEW_VARIABLE: z.string(), // Required string
  // OR
  NEW_VARIABLE: z.string().optional(), // Optional string
  // OR
  NEW_VARIABLE: z.string().default("default-value"), // With default
  // OR
  NEW_VARIABLE: z.coerce.number().default(3000), // Number with coercion
  // OR
  NEW_VARIABLE: z.string().url(), // URL validation
});

Step 2: Add to Mapping Object

Add the variable to mappedEnv using the getEnv() helper (which reads prefixed variables):

const mappedEnv = {
  // ... existing mappings ...
  NEW_VARIABLE: getEnv("NEW_VARIABLE"),
};

Step 3: Document in .env.example

Add the variable with a descriptive comment, using the prefix (default: BT_):

# Description of what this variable is for
BT_NEW_VARIABLE=example-value

Note: The prefix is defined in src/env.ts as const PREFIX = "BT". Change this when creating a new service from the template.

Step 4: Add Tests in tests/env.test.ts

Add test cases for the new variable:

it("accepts valid NEW_VARIABLE", () => {
  const parsed = envSchema.parse({ NEW_VARIABLE: "valid-value" });
  expect(parsed.NEW_VARIABLE).toBe("valid-value");
});

it("defaults NEW_VARIABLE if missing", () => {
  const parsed = envSchema.parse({});
  expect(parsed.NEW_VARIABLE).toBe("default-value");
});

// OR for optional
it("accepts missing NEW_VARIABLE", () => {
  const parsed = envSchema.parse({});
  expect(parsed.NEW_VARIABLE).toBeUndefined();
});

// OR for required
it("rejects missing NEW_VARIABLE", () => {
  expect(() => envSchema.parse({})).toThrow();
});

Common Patterns

All examples use the getEnv() helper and BT_ prefix:

Required String

// Schema
MY_API_KEY: z.string(),

// Mapping
MY_API_KEY: getEnv("MY_API_KEY"),

// .env.example
BT_MY_API_KEY=your-api-key-here

Optional String

// Schema
OPTIONAL_FEATURE: z.string().optional(),

// Mapping
OPTIONAL_FEATURE: getEnv("OPTIONAL_FEATURE"),

// .env.example
# Optional: Enable feature X
# BT_OPTIONAL_FEATURE=enabled

String with Default

// Schema
LOG_LEVEL: z.string().default("info"),

// Mapping
LOG_LEVEL: getEnv("LOG_LEVEL"),

// .env.example
BT_LOG_LEVEL=info

Number with Coercion

// Schema
RATE_LIMIT: z.coerce.number().default(100),

// Mapping
RATE_LIMIT: getEnv("RATE_LIMIT"),

// .env.example
BT_RATE_LIMIT=100

URL Validation

// Schema
WEBHOOK_URL: z.string().url().optional(),

// Mapping
WEBHOOK_URL: getEnv("WEBHOOK_URL"),

// .env.example
# Webhook endpoint for notifications
BT_WEBHOOK_URL=https://example.com/webhook

Enum Values

// Schema
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),

// Mapping
NODE_ENV: getEnv("NODE_ENV"),

// .env.example
BT_NODE_ENV=development

Boolean (as string)

// Schema
ENABLE_FEATURE: z.string().transform(v => v === "true").default("false"),

// Mapping
ENABLE_FEATURE: getEnv("ENABLE_FEATURE"),

// .env.example
BT_ENABLE_FEATURE=false

Usage in Code

Always import from @/env, never use process.env directly:

import { env } from "@/env";

// Correct
const apiKey = env.MY_API_KEY;

// Wrong - bypasses validation
const apiKey = process.env.MY_API_KEY;

Full Example: Adding Email Service Config

1. Update src/env.ts

const envSchema = z.object({
  // ... existing ...

  // Email service configuration
  EMAIL_API_KEY: z.string().optional(),
  EMAIL_FROM_ADDRESS: z.string().email().optional(),
  EMAIL_PROVIDER: z.enum(["sendgrid", "mailgun"]).default("sendgrid"),
});

const mappedEnv = {
  // ... existing ...
  EMAIL_API_KEY: getEnv("EMAIL_API_KEY"),
  EMAIL_FROM_ADDRESS: getEnv("EMAIL_FROM_ADDRESS"),
  EMAIL_PROVIDER: getEnv("EMAIL_PROVIDER"),
};

2. Update .env.example

# Email service configuration
BT_EMAIL_API_KEY=your-email-api-key
BT_EMAIL_FROM_ADDRESS=noreply@example.com
BT_EMAIL_PROVIDER=sendgrid

3. Update tests/env.test.ts

it("accepts valid email configuration", () => {
  const parsed = envSchema.parse({
    EMAIL_API_KEY: "test-key",
    EMAIL_FROM_ADDRESS: "test@example.com",
    EMAIL_PROVIDER: "mailgun",
  });
  expect(parsed.EMAIL_API_KEY).toBe("test-key");
  expect(parsed.EMAIL_FROM_ADDRESS).toBe("test@example.com");
  expect(parsed.EMAIL_PROVIDER).toBe("mailgun");
});

it("defaults EMAIL_PROVIDER to sendgrid", () => {
  const parsed = envSchema.parse({});
  expect(parsed.EMAIL_PROVIDER).toBe("sendgrid");
});

it("rejects invalid EMAIL_FROM_ADDRESS", () => {
  expect(() =>
    envSchema.parse({ EMAIL_FROM_ADDRESS: "not-an-email" }),
  ).toThrow();
});

it("rejects invalid EMAIL_PROVIDER", () => {
  expect(() => envSchema.parse({ EMAIL_PROVIDER: "invalid" })).toThrow();
});

What NOT to Do

  • Do NOT use process.env directly in application code
  • Do NOT forget to add the mapping in mappedEnv
  • Do NOT skip documenting in .env.example
  • Do NOT skip adding tests for validation rules
  • Do NOT store secrets in .env.example (use placeholder values)

See Also

  • create-utility-service - Services that use environment config
  • test-schema - Testing Zod schemas (similar patterns)

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/add-environment-variable-mmio71wo/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/add-environment-variable-mmio71wo' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/add-environment-variable-mmio71wo/download' --output '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md.part' && mv '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md.part' '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Original excerpt: Quick Reference

Files to modify:

  1. src/env.ts - Add to schema and mapping
  2. .env.example - Document the variable
  3. tests/env.test.ts - Add validation tests

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md' && test -s '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/add-env-variable' && cp -R '.skill-downloads/add-environment-variable-mmio71wo' '.claude/skills/add-env-variable'

Cursor
test -f '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md' && test -s '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/add-env-variable' && cp -R '.skill-downloads/add-environment-variable-mmio71wo' '.cursor/skills/add-env-variable'

Codex
test -f '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md' && test -s '.skill-downloads/add-environment-variable-mmio71wo/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/add-env-variable' && cp -R '.skill-downloads/add-environment-variable-mmio71wo' '.agents/skills/add-env-variable'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/add-environment-variable-mmio71wo'

openskills read 'add-environment-variable-mmio71wo'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/add-environment-variable-mmio71wo/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills