It appears some route middleware is running before index.js
, which is crashing my application because the order of execution prevents me from loading my dotenv file on time.
I would like to load my dotenv file before everything in order to make sure that all modules that require it will have access to it.
However, while debugging this issue, I noticed that a console.log
at the top of the app entry point still doesn't log first.
Folder structure:
src
------index.js
middleware
------auth.js
routes
------auth.route.js
------index.js
.env
Code that logs first middleware/auth.js
:
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'
module.exports = function() {
console.log('this prints first with undefined', process.env.JWT_SECRET) <-------
which gets called in auth.route.js
import auth from '../middleware/auth'
const userRouter = express.Router()
userRouter.get('/dashboard', auth().authenticate(), function(req, res) {
res.send('Authenticated, user id is: ' + req.user.id)
})
index.js
file:
console.log("this prints second"); <---------
(...)
import routes from './routes'
import express from 'express'
import auth from './middleware/auth'
require('dotenv').config({ silent: process.env.NODE_ENV === 'production' })
const app = express();
(...)
app.use('/api', routes);