node.jsexpressherokuhttpresponseheroku-api

How to set up environment variables on Heroku?


When I deploy Node.js API on Heroku it gives me a wrong response .

res.json({"user":user,"auth-token":token});

localhost:3000/auth/login

{
"user": {
 "email": "name1@gmail.com",
 "username": "name1",
 "fullname": "fullname 1"
},
"auth-token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiI1ZjMxN2I0OTFhZTc4YzFjOWNjMjZjZWUiLCJ1c2VybmFtZSI6Im5pa2hpbGt1bWEiLCJmdWxsbmFtZSI6Ik5pa2hpbCBrdW1hciBTaW5naCIsImlhdCI6MTU5ODI0OTA3M30"
}

After deploy on heroku

name.herokuapp.com/auth/login

{
"user": {
 "email": "name1@gmail.com",
 "username": "name1",
 "fullname": "fullname 1"
}
}

Solution

  • Follow the following steps

    Install package called dotenv

    npm install dotenv

    Load that module in the main file where you using like environment variable. e.g process.env.PORT

    require("dotenv").config();
    const express = require("express");
    const mongoose = require("mongoose");
    
    1. Now log in to Heroku account

    2. Go to your project dashboard

    3. Got to settings tab heroku setting

    4. Now add your environment variables here

    environment variables

    Now put your JWT_SECRET_KEY key and value to the next textbox there.

    Note: Put same names in here like .env file

    Hope that will work!