Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

255
Vistas
Why is req.somevariable and res.locals not working with jwt callbacks?

We have a route & a middleware like this:

When we do them like this:

//middleware
router.use((req, res, next) => {

    // check header or url parameters or post parameters for token
    let token = req.body.token || req.query.token || req.headers['x-access-token'],


        // verifies secret and checks exp
        jwt.verify(token, config.secret, (err, decoded) => {
            if (err) {
                return res.json({
                    success: false,
                    message: 'Failed to authenticate token.'
                });
            } else {
                // if everything is good, save to request for use in other routes
                res.locals.test = "test";
                req.somevariable = "variable1";

                console.log("res.locals.test inside middleware ", JSON.stringify(res.locals.test));
                console.log("req.somevariable inside middleware ", JSON.stringify(req.somevariable));

                next();

            }
        });

    next();
});

//TestRoute
router.get('/TestRoute', (req, res) => {

    console.log("res.locals.test outside middleware ", JSON.stringify(res.locals.test));
    console.log("req.somevariable outside middleware ", JSON.stringify(req.somevariable));

});

The values of req.somevariable and res.locals.test are undefined outside middleware

When we do them like this:

//middleware
router.use((req, res, next) => {

    res.locals.test = "test";
    req.somevariable = "variable1";

    console.log("res.locals.test inside middleware ", JSON.stringify(res.locals.test));
    console.log("req.somevariable inside middleware ", JSON.stringify(req.somevariable));

    next();

});

//TestRoute
router.get('/TestRoute', (req, res) => {

    console.log("res.locals.test outside middleware ", JSON.stringify(res.locals.test));
    console.log("req.somevariable outside middleware ", JSON.stringify(req.somevariable));


});

The values of req.somevariable and res.locals.test are available outside middleware.

What is the problem here?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

res.locals.VARIABLENAME = req.user

VARIABLENAME (whatever variable you set it to) can show up as undefined when you use .ejs or when dynamic rendering with that variable, you can get errors like your variable name is undefined.

THIS IS AN ODDITY with res.locals: when you want to use the variable name you set to res.locals with rendering, you have to define req.user in your function THAT RENDERS THE FILE!

Backend: res.locals.currentUser = req.user

//THIS FUNCTION WILL RENDER PERFECTLY LETTING ME USE currentUser in my .ejs file
 upgradeForm(req, res, next) {
    let saved = req.user;
    if(req.user){
      res.render("users/upgrade");
    } else{
      req.flash("notice", "You've successfully signed in!");
      res.redirect("/");
    }
  }

HOWEVER

//THIS FUNCTION WILL SAY currentUser is UNDEFINED IN MY .ejs file
 upgradeForm(req, res, next) {
    if(req.user){
      res.render("users/upgrade");
    } else{
      req.flash("notice", "You've successfully signed in!");
      res.redirect("/");
    }
  }

No code difference except for that the working function rendering has req.user set to a variable (you don't even have to use that variable). Took me 9 hours to solve this problem but now you know!

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda