'Possible to pass a parameter into Express' app.use()

I have my Node/Express server running. I have the main server.js file where most of the code is for the server. Now I want to separate out the routes into a separate file. I have done this before using app.use(routes). But the problem is, I want to pass a string in for one of the routes to use.

Here is my server.js code:

// other imports
import routes from './routes.js';

const app = express();
...
const port = Number.parseInt(process.env.PORT, 10) || 3001;
const serverType = process.env.NODE_ENV === 'production' ? 'Production' : 'Test';
const statusMsg = `${serverType} Node server for external facing web server on ${port}`;
// i want `routes` to have access to `statusMsg`
app.use(routes);

Then in routes.js:

import express from 'express';

const router = express.Router();

router.get('/', (req, res) => res.status(200).send(statusMsg);

export default router;

I use serverType and port elsewhere in server.js, else I would just move all that code to routes.js.

Update Adding in updated routes.js as I understand it with suggestion from jonrsharpe.

import express from 'express';

const router = express.Router();

const createRoutes = (statusMsg) => {
  router.get('/', (req, res) => res.status(200).send(statusMsg);
};

export default createRoutes;


Solution 1:[1]

You can separate the server logic, routes logic, and business logic (usually inside a separate file called a controller).

inside the server file try blow code:

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
require('dotenv').config();
const connectDB = require('./config/config')
const cookieParser = require('cookie-parser')
const authRoutes = require('./routes/authRoutes')
const categoryRoutes = require('./routes/categoryRoutes')
const cors = require('cors');

connectDB();

app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());


//Route Mounting
app.use('/', authRoutes);
app.use('/', categoryRoutes);



app.listen(process.env.PORT, ()=>{
    console.log(`Server is running on PORT: ${process.env.PORT}`)
})

Then create a separate file authRoute.js and do the following code

const express = require('express')
const { registerUser, loginUser, getAllUsers, logoutUser} = require('../controllers/authController')
const router = express.Router()
const {isAuthenticatedUser, isAuthorizedRoles} = require('../middleware/auth')


router.route('/user/new').post(registerUser);
router.route('/user/login').post(loginUser);
router.route('/users').get(getAllUsers);
router.route('/account/logout').get(logoutUser);

module.exports = router;

lastly to write the business logic create file authController.js and place the following code.

const User = require('../model/userSchema');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
require('dotenv').config();

exports.registerUser = async (req, re, next)=>{
    let password = req.body.password;
    password = await bcrypt.hash(password, 10);
    const newUser = req.body;
    newUser.password = password;
    try {
        const user = await User.create(newUser);
        if(user){
            res.json({
                success:true,
                user
            });
        }
    } catch (error) {
        console.log(error);
    }
}


exports.loginUser = async function(req, res){

    const email = req.body.email;
    const password = req.body.password;

    if(!email || !password){
        return res.json({
            success:false,
            message:'Please provide the email & Password'
        })
    }

    const user = await User.findOne({email:email});

    if(!user){
        return res.json({
            success:false,
            message:'user with this email not found in database'
        })
    }

    const isPasswordMatch = await bcrypt.compare(password, user.password);

    if(!isPasswordMatch){
        return res.json({
            success:false,
            message:'Your password is wrong...'
        })
    }

    const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRY_TIME });

    res.cookie('token', token, {httpOnly:true, expires:new Date(Date.now() + 60*60*1000 )}).json({
        success:true,
        message:'You are logged in! Enjoy',
    })

}


exports.getAllUsers = async (req, res, next)=>{
    res.json({
        success:true,
        data:[
            {
                "id":1,
                "name":"Yasir",
                "qual":"MCS",
                "age":32
            },
            {
                "id":2,
                "name":"Tabish",
                "qual":"BS",
                "age":21
            },
            {
                "id":3,
                "name":"Ahmed",
                "qual":"BSCS",
                "age":32
            },
            {
                "id":4,
                "name":"Hassan",
                "qual":"MCS",
                "age":33
            }
        ]
    })
}

exports.logoutUser = async (req, res, next)=>{
    res.cookie('token', null, {expires:new Date(Date.now())}).json({
        success:true,
        message:'You are loggedOut',
    }) 
}

This is the way you can have separation of concerns.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yasir Ali