All files / src/lib/core env.ts

81.33% Statements 61/75
62.5% Branches 5/8
100% Functions 2/2
81.33% Lines 61/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 761x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 92x 92x 92x 92x             92x 1x 1x 1x 1x 1x 151x 151x 151x 151x 151x 151x 151x 151x 1x 1x 1x 1x 1x 1x 1x 1x 92x 92x 92x 92x                 92x 1x 1x  
/**
 * Environment variable validation
 * Ensures all required environment variables are set at application startup
 */
 
import { logger } from './logger';
 
const requiredEnvVars = [
  "DATABASE_URL",
  "NEXTAUTH_SECRET",
  "NEXTAUTH_URL",
] as const;
 
interface EnvConfig {
  // Required
  DATABASE_URL: string;
  NEXTAUTH_SECRET: string;
  NEXTAUTH_URL: string;
 
  // Optional
  NODE_ENV: "development" | "production" | "test";
  NEXT_PUBLIC_API_URL: string;
}
 
/**
 * Validate that all required environment variables are set
 * Throws error if any are missing
 */
export function validateEnvironment(): void {
  const missingVars = requiredEnvVars.filter((envVar) => !process.env[envVar]);
 
  if (missingVars.length > 0) {
    const varList = missingVars.join(", ");
    throw new Error(
      `Missing required environment variables: ${varList}\n` +
      `Please set these variables in your .env.local file or deployment environment.`
    );
  }
}
 
/**
 * Get validated environment configuration
 * Should be called after validateEnvironment() is run
 */
export function getEnvConfig(): EnvConfig {
  return {
    DATABASE_URL: process.env.DATABASE_URL!,
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET!,
    NEXTAUTH_URL: process.env.NEXTAUTH_URL!,
    NODE_ENV: (process.env.NODE_ENV || "development") as "development" | "production" | "test",
    NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || process.env.NEXTAUTH_URL!};
}
 
/**
 * Validate environment on server startup (only in server environment)
 * Skip during build phase (NEXT_PHASE indicates build-time)
 */
const isBuildPhase = process.env.NEXT_PHASE === "phase-production-build";
 
if (typeof window === "undefined" && !isBuildPhase) {
  // Only validate in server-side code, not during build
  try {
    validateEnvironment();
  } catch (error) {
    if (process.env.NODE_ENV === "production") {
      // In production runtime, fail fast
      throw error;
    } else {
      // In development, log warning but don't fail
      logger.warn("ENV", `Environment validation warning: ${error instanceof Error ? error.message : error}`);
    }
  }
}
 
export const env = getEnvConfig();