I have a full-stack project with a client
and server
directories, each with their own packages. An .env
file is located in server
directory; dotenv
package is in the same directory.
I’m trying to get .env
to be found and read in my server
directory, but only my test data seeds.js
file is able to capture the env variable it needs to talk to MongoDB, while my server.js
can’t grab any.
Root has client
and server
directories for front-end and back-end. My problem resides in server
.
server
|--config
| |--connection.js
|
|--models
|--node_modules <part of .gitignore
|--schemas
|--seeders
| |--cleanDB.js
| |--seeds.js
|
|--utils
| |--auth.js
| |--dateFormat.js
|
| .env <part of .gitignore
| .gitignore
| package-lock.json
| package.json
| server.js
| vercel.json
In my .env
is the following:
MONGODB_URI=mongodb+srv://[USERNAME]:[PASSWORD]@adncluster.8xdqpdg.mongodb.net/[DBNAME]?retryWrites=true&w=majority
JWT_TOKEN=[REDACTED]
JWT_EXP=2h
PORT=3001
config
directory houses connection.js
that initiates a connection to MongoDB. It’s also where require.('dotenv').config()
is located since there are two other js files trying to talk to this js file – server.js
and seeds.js
. seeds.js
is located under seeders
directory.
connection.js
:
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI);
module.exports = mongoose.connection;
Both server.js
and seeds.js
start with a const db
declaration, obviously with a small path adjustment due to their locations:
server.js
:
const db = require('./config/connection');
seeds.js
:
const db = require("../config/connection");
According to my console log, seeds.js
is able to populate the database with test data, whereas server.js
is grabbing undefined
env variables before an error log is thrown, stating MongooseError
ran into an undefined
URI parameter. Neither js file has a dotenv
config line.
I’ve tried customizing the dotenv line to be require('dotenv').config({ path: "./.env" })
and still the same undefined
for server.js
.
This is where I am stuck. The token and expiration are being requested from a middleware auth.js
located in utils
directory, but it is called upon via server.js
.
Alex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.