πŸ’‘ Key Takeaways

  • Use .env files and process.env for configuration
  • Prefix client-accessible variables with NEXT_PUBLIC_
  • Avoid committing secrets and remember server vs client scope

πŸ”‘ .env Files

  • .env – loaded in all environments
  • .env.local – local overrides, never commit
  • .env.development, .env.production, .env.test – environment-specific
# Example
DATABASE_URL=postgres://user:pass@host:5432/db
SECRET_KEY=mysecret
NEXT_PUBLIC_API_URL=https://api.example.com

βš™οΈ Using Environment Variables in Code

  • Server-only variables do not have NEXT_PUBLIC_ prefix
  • Only accessible in server components, API routes, or middleware
  • Safe for secrets
// server-only
const secret = process.env.SECRET_KEY;
  • Public variables must use NEXT_PUBLIC_ prefix
  • Accessible in both client and server code
  • Use for API URLs, feature flags, analytics
const apiUrl = process.env.NEXT_PUBLIC_API_URL;

πŸ“‚ Access in App Directory

  • Use process.env in server components, API routes, middleware
  • Cannot access server-only variables directly in client components
  • Pass values via props or use public variables
// Server Component
export default function Page() {
  const apiUrl = process.env.NEXT_PUBLIC_API_URL;
  return <div>API URL: {apiUrl}</div>;
}

⚑ Runtime Configuration (next.config.js)

  • Define build-time variables using env
  • .env files are preferred for secrets and environment-specific values
// next.config.js
module.exports = {
  env: {
    CUSTOM_VAR: 'value', // build-time variable
  },
};

πŸ›‘οΈ Best Practices

  • Never commit secretsβ€”use .env.local for local development
  • Restart dev server after changing .env files
  • Use NEXT_PUBLIC_ prefix for variables needed in the browser
  • Good for API endpoints, feature flags, analytics keys
  • For dynamic runtime config, rely on platform secrets or dashboard

⚠️ Gotchas

  • process.env is statically replaced at build time – dynamic changes require rebuild
  • Only variables referenced in code are included in the bundle
  • Avoid exposing secrets by accidentally using NEXT_PUBLIC_ prefix

Disclaimer: The information provided on this website is for educational and informational purposes only. Health-related content is not intended to serve as medical advice, diagnosis, or treatment recommendations and should not replace consultation with qualified healthcare professionals. Financial content is for educational purposes only and does not constitute financial advice, investment recommendations, or professional financial planning services. Always consult with licensed healthcare providers for medical concerns and qualified financial advisors for personalized financial guidance.