Blog>
Snippets

Environment Variable Validation with next-env

Give an example of using the next-env library to validate and load environment variables during the build time.
import { loadEnvConfig } from '@next/env';

// Run environment variable validation and loading
const projectDir = process.cwd();
loadEnvConfig(projectDir);

// Here you would normally add your logic to validate
// specific environment variables as required for your application
Loads environment variables using 'loadEnvConfig' from '@next/env' at the specified project directory (usually current working directory). After loading, additional application-specific validation logic can be implemented.
import { cleanEnv, str, num } from 'envalid';

// Define the environment variable schema
const envSchema = {
    DATABASE_URL: str(),
    PORT: num({ default: 3000 })
};

// Validate and clean the process.env object
const validatedEnv = cleanEnv(process.env, envSchema);

// Now process.env contains only the validated and cleaned env vars
console.log('Validated Environment Variables:', validatedEnv);
Uses 'envalid' to validate specific environment variables according to the defined schema, which includes a string for 'DATABASE_URL' and a number for 'PORT' with a default value of 3000. It then logs the validated environment variables.