Express.js application entry point

It seems like some route middleware is running up index.js, which causes my application to crash because the execution order does not allow me to download my dotenv file on time.

I would like to download my dotenv file before making sure that all modules that require it will have access to it.

However, when debugging this problem, I noticed that console.logthe top of the entry point to the application is still not logged in first.

Folder structure:

src
------index.js
middleware
------auth.js
routes
------auth.route.js
------index.js
.env

The code that is registered 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 is 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);
-3
source share
1 answer

, , , , auth.route.js.

, auth.route.js index.js, , middleware/auth ( , ). , , , , :

, , . middleware/auth, , , . auth.route.js - , :

auth middleware/auth, userRouter.get(). auth().

auth.route.js ( , ), , auth .

, ? : auth.route.js , , , :

auth.route.js

import auth from '../middleware/auth'

const userRouter = express.Router()

export default () => {
  userRouter.get('/dashboard', auth().authenticate(), function(req, res) {
    res.send('Authenticated, user id is: ' + req.user.id)
  })

  return userRouter;
}

(.. ).

import getRouter from './modules/auth.route.js';

app.use('/api', getRouter());
0

Source: https://habr.com/ru/post/1669987/


All Articles