skip to Main Content

I have a .env file which is the following:

PORT=5000

I first run source .env to load the environnement variables.
When I run echo $PORT, I see that the variable is set to 5000.

But, as soon as I run my nodeJS script, which contains

if(process.env.PORT === undefined) throw new Error("Missing PORT in process.env");

It throws an error because the PORT is undefined.
Even after running the script echo $PORT is still 5000.

The expected behavior is that process.env.PORT is 5000.

2

Answers


  1. as Pointy mentioned it you can pass your environment variable when you start your script.
    If you prefer to use a .env file and want to access its variables during will have to install and use the dotenv package.

    Two way for doing that.

    • When you start your script : node -r dotenv/config scriptname.js
    • By importing the dotenv package at the start of your script : require(‘dotenv’).config();

    google research: node js process env
    answer source: https://nodejs.dev/en/learn/how-to-read-environment-variables-from-nodejs/

    Login or Signup to reply.
  2. Install the dotenv package and import or require dotenv in your index.js file.

    const express = require("express");
    
        require("dotenv").config();
        
        
        app.listen(PORT, () => {
            console.log(`listening at port ${process.env.PORT}`)
        })
    

    Make sure you restart your server after importing the dotenv config.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search