Search code examples
node.jsexpressrequestundefined

Express: 4.17: Passing the variable to the next function returns undefined (middleware)


Issue I am trying to pass my variable, req.app.locals.userId down to the /getuser route. Now I have tried with and without app in req.app.locals.userId. The issue is the variable keeps returning undefined in my /getuser route. I have tried to run the middleware directly in the router and the variable returns correctly, but it seems like req.app.locals does not work when I am using it as a middleware. req.app.locals returns an Object which means that req.app.locals works.

const verifyJWT = (req, res, next) => {
    const token = req.headers["x-access-token"]
    if (!token) {
        res.send("We need a token")
    } else {
        jwt.verify(JSON.parse(token), "jwtSecret", (err, decoded) => {
            if (err) {
                res.json({ auth: false, message: "You failed to authenticate" })
            } else {
                req.app.locals.userId = decoded.id;  //This is the variable I am trying to get
                next();
            }
        })
    }
}
router.route("/getuser", verifyJWT).get((req, res) => {

    console.log(req.app.locals.userId) // <--- Returns undefined


});

I just can't see what I am doing wrong.

My index file

const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const bp = require('body-parser');

const auth = require("./routes/auth");

const PORT = process.env.PORT || 3003;
const app = express();

app.use(cors());
app.use(express.json());

app.use("/auth", auth);

app.get("/", (req, res) => {
    console.log("/");
});


app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Solution

  • Index file and your controller appear fine once working on your route file.

    router.route("/getuser", verifyJWT).get((req, res) => {
    
        console.log(req.app.locals.userId) // <--- Returns undefined
    
    
    });
    

    Instead of this try to get req...

      router.get("/getuser", verifyJWT, (req, res, next) => {
         console.log(req.app.locals.userId);
         });