next.jsenvironment-variables

Next.js, Check if required environment variables are defined on startup


When setting up an existing Next.js project, it's easy to forget to create and configure the .env file (or .env.local or similar). It would be handy if, when starting the server, it would assert that some required variables are undefined, so that you get an error early on instead of a runtime error later when the variable happens to be used in the code.

Something like:

npm run dev
> next dev
...
Error: the DATABASE_URL environment variable is empty or undefined

Is this possible? Or maybe there is some other good practice that makes the problem less relevant.


Solution

  • you can create a file something like checkEnv.js and run it before next dev like here

    "scripts": {
      "dev": "node checkEnv.js && next dev",
      "build": "node checkEnv.js && next build",
      "start": "node checkEnv.js && next start"
    }
    

    and put some function to validate env variables in checkEnv.js like

       require('dotenv').config(); 
        const requiredVariables = ['DATABASE_URL', 'OTHER_REQUIRED_VARIABLE'];
            
            requiredVariables.forEach(variable => {
              if (!process.env[variable]) {
                console.error(`Error: The ${variable} environment variable is empty or undefined`);
                process.exit(1); // Exit with an error code
              } else {
        console.info('All Variables are available');
      }
            });
    

    log when all variables are available log when all variables are available

    log when any .env variable isn't available or empty log when any .env variable isn't available or empty