Node.js responde previamente con Express

So I'm doing a web page with Node.js and Express framework. I already have registration and login (I'm holding users id in a session). Next step is to render different page whenever a user is authenticated.

Some of those pages require a User object which is just a mapping of a user from my db. So whenever an authenticated request comes I need to retrieve the user from my db. But writing this code every time seems to be a bad way to do this. So here's the question: is it possible (and if it, then how?) to do, say preresponse, so I can automaticaly retrieve User object whenever I know that the user is authenticated and THEN do the main response?

preguntado el 08 de noviembre de 11 a las 16:11

Can't you just store the User object in the session? -

Not really, because the content may change and I want to be sure, that every time I make response I have the correct data. Hmm, but perhaps you're right. Maybe I should redesign it. -

2 Respuestas

Middleware is what you are referring to. Middleware is just a function that gets called sequentially when the route is triggered. So to have a loadUser function:

function loadUser(req, res, next) {
  // You would fetch your user from the db
  var user = users[];
  if (user) {
    req.user = user;
  } else {
    next(new Error('Failed to load user ' +;

app.get('/user/:id', loadUser, function(req, res){
  res.send('Viewing user ' +;

You can define as many middleware functions as your need. Just be sure to call next() at the end to pass the route handling on to the next function.

respondido 08 nov., 11:22

Beautiful, thank you very much! This is exactly what I need! As Peter Lyons mentioned this is all covered in Express documentation. I looked there but I have no idea why I missed it. :) Thanks again! I marked your answer, because Peter Lyons has more points. :) - monstruoso

This EXACT example is covered in the express.js route middleware docs. Go read it and you'll see the pattern of using middleware to factor out common functionality that you need at many route paths in your app.

respondido 08 nov., 11:21

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.