Manage environment variables securely across different environments
# Environment Variables Best Practices for Google Antigravity
Master environment variable management in your Google Antigravity projects with secure configuration, validation, and runtime safety patterns. This guide covers development workflows, secrets management, and production deployment strategies.
## Type-Safe Environment Configuration
Create validated environment schemas:
```typescript
// src/env.ts
import { z } from "zod";
const envSchema = z.object({
// App Configuration
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
APP_URL: z.string().url(),
PORT: z.coerce.number().default(3000),
// Database
DATABASE_URL: z.string().min(1),
DATABASE_POOL_SIZE: z.coerce.number().min(1).max(100).default(10),
// Authentication
JWT_SECRET: z.string().min(32),
JWT_EXPIRES_IN: z.string().default("7d"),
// Third-party Services
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
STRIPE_WEBHOOK_SECRET: z.string().startsWith("whsec_"),
// Email
SMTP_HOST: z.string().optional(),
SMTP_PORT: z.coerce.number().optional(),
SMTP_USER: z.string().optional(),
SMTP_PASS: z.string().optional(),
// Feature Flags
ENABLE_ANALYTICS: z.coerce.boolean().default(false),
ENABLE_MAINTENANCE_MODE: z.coerce.boolean().default(false),
// Client-side (NEXT_PUBLIC_*)
NEXT_PUBLIC_APP_URL: z.string().url(),
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: z.string().startsWith("pk_"),
NEXT_PUBLIC_GA_ID: z.string().optional(),
});
// Separate client and server schemas
const clientSchema = envSchema.pick({
NEXT_PUBLIC_APP_URL: true,
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: true,
NEXT_PUBLIC_GA_ID: true,
});
const serverSchema = envSchema.omit({
NEXT_PUBLIC_APP_URL: true,
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: true,
NEXT_PUBLIC_GA_ID: true,
});
// Validate and export typed env
function validateEnv() {
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
console.error("❌ Invalid environment variables:");
console.error(parsed.error.flatten().fieldErrors);
throw new Error("Invalid environment variables");
}
return parsed.data;
}
export const env = validateEnv();
// Type exports for use throughout the app
export type Env = z.infer<typeof envSchema>;
export type ClientEnv = z.infer<typeof clientSchema>;
export type ServerEnv = z.infer<typeof serverSchema>;
```
## Environment File Structure
Organize environment files properly:
```bash
# .env.example - Template for developers
# Copy this to .env.local and fill in values
# App
NODE_ENV=development
APP_URL=http://localhost:3000
PORT=3000
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
# Authentication
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
# Stripe (use test keys for development)
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
# Public (exposed to browser)
NEXT_PUBLIC_APP_URL=http://localhost:3000
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx
```
```typescript
// .env.development.local
NODE_ENV=development
DATABASE_URL=postgresql://localhost:5432/myapp_dev
// .env.test.local
NODE_ENV=test
DATABASE_URL=postgresql://localhost:5432/myapp_test
// .env.production.local (never commit this!)
NODE_ENV=production
DATABASE_URL=postgresql://prod-server:5432/myapp
```
## Dynamic Environment Loading
Load environment variables dynamically:
```typescript
// src/lib/config.ts
import { env } from "@/env";
interface AppConfig {
app: {
name: string;
url: string;
isProduction: boolean;
isDevelopment: boolean;
};
database: {
url: string;
poolSize: number;
};
auth: {
jwtSecret: string;
jwtExpiresIn: string;
sessionMaxAge: number;
};
stripe: {
secretKey: string;
webhookSecret: string;
publishableKey: string;
};
features: {
analytics: boolean;
maintenanceMode: boolean;
};
}
export const config: AppConfig = {
app: {
name: "My App",
url: env.APP_URL,
isProduction: env.NODE_ENV === "production",
isDevelopment: env.NODE_ENV === "development",
},
database: {
url: env.DATABASE_URL,
poolSize: env.DATABASE_POOL_SIZE,
},
auth: {
jwtSecret: env.JWT_SECRET,
jwtExpiresIn: env.JWT_EXPIRES_IN,
sessionMaxAge: 60 * 60 * 24 * 7, // 7 days
},
stripe: {
secretKey: env.STRIPE_SECRET_KEY,
webhookSecret: env.STRIPE_WEBHOOK_SECRET,
publishableKey: env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,
},
features: {
analytics: env.ENABLE_ANALYTICS,
maintenanceMode: env.ENABLE_MAINTENANCE_MODE,
},
};
// Helper to get required env var with clear error
export function getRequiredEnv(key: string): string {
const value = process.env[key];
if (!value) {
throw new Error(`Missing required environment variable: ${key}`);
}
return value;
}
// Helper for optional env vars with defaults
export function getOptionalEnv(key: string, defaultValue: string): string {
return process.env[key] ?? defaultValue;
}
```
## Secrets Management Integration
Integrate with cloud secrets managers:
```typescript
// src/lib/secrets.ts
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const secretsClient = new SecretsManagerClient({ region: process.env.AWS_REGION });
interface SecretCache {
value: Record<string, string>;
expiresAt: number;
}
const cache = new Map<string, SecretCache>();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
export async function getSecret(secretName: string): Promise<Record<string, string>> {
// Check cache first
const cached = cache.get(secretName);
if (cached && cached.expiresAt > Date.now()) {
return cached.value;
}
try {
const command = new GetSecretValueCommand({ SecretId: secretName });
const response = await secretsClient.send(command);
if (!response.SecretString) {
throw new Error(`Secret ${secretName} is empty`);
}
const secretValue = JSON.parse(response.SecretString);
// Update cache
cache.set(secretName, {
value: secretValue,
expiresAt: Date.now() + CACHE_TTL,
});
return secretValue;
} catch (error) {
console.error(`Failed to fetch secret ${secretName}:`, error);
throw error;
}
}
// Load secrets into environment at startup
export async function loadSecretsToEnv(): Promise<void> {
if (process.env.NODE_ENV !== "production") {
return; // Use .env files in development
}
const secrets = await getSecret("myapp/production");
for (const [key, value] of Object.entries(secrets)) {
if (!process.env[key]) {
process.env[key] = value;
}
}
}
```
## Environment Validation Middleware
Validate environment at runtime:
```typescript
// src/lib/validateEnv.ts
interface ValidationRule {
name: string;
check: () => boolean;
message: string;
severity: "error" | "warning";
}
const validationRules: ValidationRule[] = [
{
name: "jwt-secret-length",
check: () => (process.env.JWT_SECRET?.length ?? 0) >= 32,
message: "JWT_SECRET must be at least 32 characters",
severity: "error",
},
{
name: "production-https",
check: () => {
if (process.env.NODE_ENV !== "production") return true;
return process.env.APP_URL?.startsWith("https://") ?? false;
},
message: "APP_URL must use HTTPS in production",
severity: "error",
},
{
name: "analytics-configured",
check: () => {
if (!process.env.ENABLE_ANALYTICS) return true;
return !!process.env.NEXT_PUBLIC_GA_ID;
},
message: "GA_ID required when analytics is enabled",
severity: "warning",
},
];
export function validateEnvironment(): void {
const errors: string[] = [];
const warnings: string[] = [];
for (const rule of validationRules) {
if (!rule.check()) {
if (rule.severity === "error") {
errors.push(`❌ ${rule.name}: ${rule.message}`);
} else {
warnings.push(`⚠️ ${rule.name}: ${rule.message}`);
}
}
}
if (warnings.length > 0) {
console.warn("Environment warnings:\n" + warnings.join("\n"));
}
if (errors.length > 0) {
console.error("Environment errors:\n" + errors.join("\n"));
throw new Error("Environment validation failed");
}
console.log("✅ Environment validation passed");
}
```
Google Antigravity generates secure environment configurations with proper validation, type safety, and secrets management for production-ready applications.This Environment prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their environment implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Environment projects, consider mentioning your framework version, coding style, and any specific libraries you're using.