.env environment variables not working Express

I am using the Express server as in this Add Authentication to Existing Node.js/Express Apps with Auth0 -- Express and Authentication Series - YouTube but getting an error whenever I use environment variables in my config.

const express = require("express");
const bodyParser = require("body-parser");
const { auth } = require("express-openid-connect");
const PORT = process.env.PORT || 3005;
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");

const config = {
    authRequired: false,
    auth0Logout: true,
    secret: process.env.APP_SESSION_SECRET,
    baseURL: process.env.BASE_URL,
    clientID: process.env.CLIENT_ID,
    issuerBaseURL: process.env.ISSUER_BASE_URL

const app  = express();

app.use(bodyParser.urlencoded({ extended: true }));
// middleware, method returns middleware
// used in request
//can be handled in regards to payloads
//query strings and post type payloads that might contain json
//url encoded query strings. Extended data, so we can handled 
//nested data coming in query strings

//auth router attaches /login, /logout and /callback router to baseURL

app.use("/api/", indexRouter);
app.use("/api/users", usersRouter);

app.listen(PORT, () => {
    console.log(`server listening on port ${PORT}`)

not sure what I’m doing wrong!

Hey there!

Thanks for asking. Reaching out to @bendechrai (the video author) to see if he can help us on that front. Thank you!

Hi @izzybolt95!

A couple of questions to make sure you’re on track :slight_smile:

Can you confirm where in the file system the .env file is located? It should be in the document root, is that right?

If so, have you restarted node since saving the changes to the .env file?

If yes, can you paste the contents of the .env file in here without the actual values? I don’t want you to share secrets and private information.

Also, if all of this is looking fine, can you confirm if the output of the following code, added after you define the config object, looks accurate? Feel free to share here if you like, but remember to sanitize and not share sensitive information…

console.log("App Session Secret = " + process.env.APP_SESSION_SECRET);
console.log("Base URL = " + process.env.BASE_URL);
console.log("Client ID = " + process.env.CLIENT_ID);
console.log("Issuer Base URL = " + process.env.ISSUER_BASE_URL);


1 Like

Hi Ben

Thanks for getting back to me. :slight_smile:

here’s my .env code, in the root of my project

APP_SESSION_SECRET:'some long string'

The outputs of the console.logs are strangely all undefined:

App Session Secret = undefined
Base URL = undefined
Client ID = undefined
Issuer Base URL = undefined

in my package.json file I have "dotenv": "^10.0.0" installed


I just realised my problem :no_mouth: an error in my .env file… No it’s working again! Thanks for your help!


No worries! We’ve all been there!