Skip to content

Can’t access API-key from .env-file

We are having problem accessing the API-key from our .env file when trying to fetch in our server.js. If we add the API-key manually to the URL in server.js it works, so the problem seems to be the connection between server.js and .env-file. We have npm installed dotenv. In the .env file we have written the key like this: WEATHER_API_KEY = XXXXXXXXXXXX

Does anyone know what we have done wrong?

import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import crypto from "crypto";
import bcrypt from "bcrypt";
import request from "request";
import dotenv from "dotenv";
// import { stringify } from "querystring";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = Promise;

const port = process.env.PORT || 8080;
const app = express();


app.get("/home", (req, res) => {
  let city =;
  // const request = require("request");
  // const options = {
  //   url: `${city}&appid=${process.env.WEATHER_API_KEY}`,
  //   method: "GET",
  //   headers: {
  //     Accept: "application/json",
  //   },
  // };
  const key = "*******************";
  const requesturl = `${city}&appid=${key}`;
  request(requesturl, function (error, response, body) {
    let data = JSON.parse(body);
    if (response.statusCode === 200) {
      res.send(`The weather in ${city} is ${[0].description}`);
    } else {



You may try this

import 'dotenv/config';

in place of import dotenv from "dotenv"; and remove the dotenv.config(); call.

Source and explanation:

And update the request URL (which you might have changed for testing purpose) to

const requesturl = `${city}&appid=${process.env.key}`;

Also, try defining your key without any spaces, though this is less likely to be the root cause.