Ajouter une variable d'environnement

VérifiéSûr

Ajoute une nouvelle variable d'environnement avec validation Zod. Modifiez src/env.ts, .env.example et les tests pour intégrer la configuration.

Spar Skills Guide Bot
DeveloppementDébutant
09/03/2026
Claude CodeCursorWindsurfCodex
#environment-variables#zod#configuration#typescript#validation

Recommandé pour

Synthèse automatique

Ajoute une variable d'environnement validée par Zod dans src/env.ts, la documente dans .env.example et complète les tests de validation.

Points forts

  • Couvre tout le cycle : schéma Zod, objet de mapping, documentation .env.example et tests
  • Fournit des patrons prêts à l'emploi pour les cas courants (optionnel, valeur par défaut, nombre coercé, URL, enum, booléen)
  • Impose l'import depuis @/env plutôt que l'accès direct à process.env

Limites

  • Suppose une structure de projet précise (src/env.ts, helper getEnv, préfixe BT_) issue d'un template
  • Ne traite ni la gestion des secrets ni la propagation de la variable dans les environnements de déploiement
  • Dépend entièrement de Zod pour la validation
Quand l'utiliser

À utiliser lorsqu'on ajoute une configuration pour un service externe, un feature flag ou un réglage applicatif dans un projet TypeScript structuré autour de src/env.ts.

Quand l'éviter

À éviter sur un projet qui n'utilise pas Zod ou cette organisation de fichiers d'environnement, ou lorsqu'il s'agit de gérer des secrets en production.

Analyse de sécurité

Sûr
Score qualité84/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.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

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)

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/add-environment-variable-mmio71wo/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

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. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Extrait original : 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

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

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 doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/add-environment-variable-mmio71wo'

openskills read 'add-environment-variable-mmio71wo'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/add-environment-variable-mmio71wo/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires