skip to Main Content

API_KEY is showing as ‘undefined’ when I set it up as an environment variable

My API_KEY is showing as ‘undefined’ when I set it up as an environment variable. The API call works when I hard code the API Key, so it’s not an issue with the key. I can also see that value of it is ‘undefined’ in the logs. I am trying to access it from a backend server (server.js) built with express. I created a separate .env file in the root of the project’s backend directory (at the same level with server.js).

I’ve installed dot env and included ‘import dotenv from dot env’ and dotenv.config in my server.js file. I’m including my server.js, .env, and package.json files below.

server.js

import express from "express";
import cors from "cors";
import axios from "axios";
import dotenv from "dotenv";

dotenv.config();

const PORT = 8000;

const app = express();

app.use(cors());

app.get("/hello", (req, res) => {
  res.json("Hello World");
});

app.get("/test-cases", async (req, res) => {
  
  const API_KEY = process.env.REACT_APP_OPENAI_API_KEY;
  console.log(API_KEY);

.env

# Not a real API KEY!!!!!
REACT_APP_OPENAI_API_KEY=sk-NgPdmiXotwLWvasdsddsfkFJG4bnvnod3BwRPTsPaeUv

package.json

{
  "name": "test-genie-backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start-backend": "nodemon src/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^1.4.0",
    "cors": "^2.8.5",
    "dotenv": "^16.1.0",
    "express": "^4.18.2"
  }
}

2

Answers


  1. Maybe try this:

    import * as dotenv from 'dotenv'
    dotenv.config()
    
    Login or Signup to reply.
  2. Replace your import statement to:

    import * as dotenv from 'dotenv'
    

    or try to use require syntax

    const dotenv = require("dotenv");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search