I am working on a Next.js project and need to configure environment variables that change depending on the execution environment (dev, staging, production), but I want to build the project only once and reuse the same build across different environments. Additionally, I want to avoid storing sensitive information in the code repository.
Requirements:
Single build: The build should be done once and then deployed to different environments.
Security: Environment variables should not be stored directly in the code repository.
Flexibility: Each environment should be able to load its own variables at deployment time.
I know that Next.js supports environment variables through .env.local, .env.development, .env.production, etc., but these variables are hardcoded at build time, making it difficult to modify them later without rebuilding the project.
Question:
What is the best way to configure Next.js environment variables so they can change between environments without requiring a new build?
What I've tried:
Using .env.* files, but the variables get hardcoded during the build.
Setting environment variables at the OS level, but Next.js only reads them at build time.