316

I want to pass some variable from the first middleware to another middleware, and I tried doing this, but there was "req.somevariable is a given as 'undefined'".


//app.js
..
app.get('/someurl/', middleware1, middleware2)
...

////middleware1
...
some conditions
...
res.somevariable = variable1;
next();
...

////middleware2
...
some conditions
...
variable = req.somevariable;
...
Jonas
  • 121,568
  • 97
  • 310
  • 388
user2791897
  • 3,179
  • 2
  • 12
  • 7
  • 2
    Should work. Unless it's a typo in the question you probably fail because you assign the value to `res` in middleware1 and try to get it from `req` in middleware2. – Andreas Hultgren Sep 18 '13 at 14:44
  • 2
    `Local variables are available in middleware via req.app.locals` http://expressjs.com/pt-br/api.html#app.locals – Ronnie Royston Dec 24 '18 at 19:48

8 Answers8

677

v4.x API docs

This is what the res.locals object is for. Setting variables directly on the request object is not supported or documented. res.locals is guaranteed to hold state over the life of a request.

Quote from the docs:

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

app.use(function(req, res, next) {
    res.locals.user = req.user;  
    res.locals.authenticated = !req.user.anonymous;
    next();
});

To retrieve the variable in the next middleware:

app.use(function(req, res, next) {
    if (res.locals.authenticated) {
        console.log(res.locals.user.id);
    }
    next();
});
cchamberlain
  • 17,444
  • 7
  • 59
  • 72
  • 30
    res.locals is intended to be used by **views** that are eventually rendered during the lifecycle of the request, this is what the documentation is saying. If you are not using views it is overkill to put things on the locals object and it is *not* the convention. In these cases, I tend to encourage people to stick with the convention so that we can reduce cognitive load while learning concepts like Express or request lifecycles. – real_ate Feb 21 '17 at 09:54
  • 3
    @real_ate that is the primary usage of res.locals, however it doesn't address OPs question. Passing request scoped variables to future middleware is sometimes a necessity, the times I've had it come up is typically around user authentication in an early middleware which sets claims that get routed in a downstream middleware. – cchamberlain Feb 21 '17 at 16:07
  • And then how to you retrieve the variable in the next middleware call? – CodyBugstein Jan 19 '18 at 19:13
  • 1
    @CodyBugstein - They should remain on the locals object. Added an example. – cchamberlain Jan 19 '18 at 21:14
  • 32
    The express documentation for writing middleware sets variables on the `req` object https://expressjs.com/en/guide/writing-middleware.html. Look at the section `Middleware function requestTime` – Catfish Jan 10 '19 at 01:18
  • 3
    This was the way you'd do it before they added `res.locals` so might be old docs. `res.locals` is a namespace specifically for this. Mutating request could be dangerous as there are reserved properties and evolving standards. – cchamberlain Jan 10 '19 at 01:28
  • 2
    It's still valid because there are too many middleware libraries that don't give you the res object. Almost every time I've needed to do this, `res.locals` was a non-starter. `multer` and `express-http-proxy` are two prominent examples. For this reason, I think @real_ate 's comment hits the nail on the head. – Rob Cannon Apr 10 '19 at 20:23
  • That's what forks and PRs are for in open source. – cchamberlain Apr 25 '19 at 12:39
  • 1
    After placing this variable on the response object, it should probably be removed before sending a response back to the client if it's not your intention to return that dataset along with the rest of your payload – goonerify Feb 15 '20 at 02:01
  • 7
    @goonerify thats luckily not how response works. Responses are transmitted by calling a functional property of the response object such as `res.json({})`, etc. `res.locals` is only available on the back-end over the life of the request. https://expressjs.com/en/5x/api.html – cchamberlain Feb 20 '20 at 00:10
  • 2
    I said this on the "marked correct" answer, but I'll add it here, too: Where is `res.locals` recommended? The API documentation you all keep referring to seems to indicate that the res.locals field is for passing data to views when using `res.render`. In fact, middleware like `express.json()` extends `req`, which seems to contradict the advice given here? – Niels Abildgaard Mar 15 '22 at 16:00
  • @NielsAbildgaard OP wants request scoped local variables that can be accessed across middlewares. _An object that contains response local variables scoped to the request_ - seems pretty clear to me. One of the main reasons you'd use it is to expose things to views. A middleware library like `express.json()` is about the only use case I could see for arguing in favor of `req` since they are going to want to avoid collisions with user level variables occupying `res.locals`. They have unit tests and maintainers. If a future change adds a new field to `req` and you named your field that.. – cchamberlain Mar 16 '22 at 18:37
  • 1
    I wrote a whole long answer with data for why res.locals is specifically for res.render and always has been. If you check the linked Github PR you'll see the maintainers agreeing, and that we are clarifying the docs. https://stackoverflow.com/a/71487552/1080564 – Niels Abildgaard Mar 16 '22 at 23:22
  • 1
    The documentation has now been updated (c.f. my updated answer, linked in my last comment). I don't want to seem rude by editing your answer, as we seem to disagree on the correct approach, but I think it would make sense to update the documentation you cite to be the current version :-) – Niels Abildgaard Mar 25 '22 at 13:17
  • 1
    Small note: req.locals is specific to Express. If using another Connect based framework, you may need to manually init "req.locals" to an empty object in order to be able to reuse some Express middlewares. – Eric Burel Aug 16 '22 at 14:52
279

Attach your variable to the res.locals object, not req.

Instead of

req.somevariable = variable1;

Have:

res.locals.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.

Amberlamps
  • 39,180
  • 5
  • 43
  • 53
  • 35
    use res.locals.variable = var; see the other answer – godzsa Mar 10 '17 at 08:36
  • 4
    to retrieve the variable, use req.res.locals.variable in next middleware function – William Wu Jan 17 '18 at 16:43
  • 5
    @WilliamWu its `res.locals`, not `req.res.locals`. – cchamberlain Jan 20 '18 at 00:56
  • 2
    `res.locals.myVar` is the way to go. – jasonseminara Mar 23 '18 at 19:05
  • 8
    Sorry for asking, but now I'm confused. Is this contradictory answer. First you suggested to do it `req.somevariable = variable1;` and then you suggested to use `res.locals`. Maybe I missed something, if someone can explain me better? – Predrag Davidovic Nov 04 '20 at 10:04
  • @PredragDavidovic had the same issue, but with the other answers it is `res.locals` what you are looking for. Really should reconsider the selected answer. – dilantha111 Nov 28 '20 at 00:13
  • 1
    there seems to be contradictory information in this accepted answer – java-addict301 Dec 05 '20 at 07:51
  • 4
    Where is `res.locals` recommended? The API documentation you all keep referring to seems to indicate that the res.locals field is for passing data to views when using `res.render`. In fact, middleware like `express.json()` extends `req`, which seems to contradict the advice given here? – Niels Abildgaard Mar 15 '22 at 16:00
  • This is the right way to do it, `res.locale` (note that I used `res` and not `req`) is only used when you need to render a view and need data to be passed to that view, otherwise it's convention to pass data (using `req`) as shown in this answer. – Sujit Dec 01 '22 at 15:35
45

I don't think that best practice will be passing a variable like req.YOUR_VAR. You might want to consider req.YOUR_APP_NAME.YOUR_VAR or req.mw_params.YOUR_VAR.

It will help you avoid overwriting other attributes.

Niels Abildgaard
  • 2,662
  • 3
  • 24
  • 32
Doron Segal
  • 2,242
  • 23
  • 22
  • 2
    How do you suggest to set `req.YOUR_APP_NAME = {}` initially? You just try to write to `req.YOUR_APP_NAME.someVar` you will get an error as `req.YOUR_APP_NAME` is not defined yet. – Kousha Oct 14 '15 at 23:40
  • 2
    @Kousha You can write router middleware at the top of your routing script: `router.use(function(req,res,next){req.YOUR_APP_NAME = {};next()})` – Tomas Feb 07 '16 at 01:22
  • is there a way to pass it as param with the next() function? like next(myObj) – philx_x Jun 14 '16 at 22:01
  • 1
    @Kousha - Your undefined error has nothing to do with express, its you trying to assign a property to an object that does not exist. Typically to do this you would use `req.APP_NS = req.APP_NS || {}; req.APP_NS.somevar = 'value'`. – cchamberlain Jul 13 '16 at 04:25
  • 1
    @philx_x, if you pass any parameter to `next` function, it will trigger express' error handler and drop out. check the docs. – Merl Jan 09 '18 at 20:00
34

The most common pattern for passing variables on to other middleware and endpoint functions is attaching values to the request object req.

In your case, that would mean having middlewares such as these:

app.use(function (req, res, next) {
  req.someVariable = 123;
  next();
});

app.use(function (req, res, next) {
  console.log("The variable is", req.someVariable);
  next();
});

There are many common use cases of this pattern, and it is the standard way of doing it in the express community. See, for example:


It is worth noting that the currently most highly voted answer incorrectly recommends using res.locals for this purpose---which seems to stem from a misreading of the documentation. For that reason, I'll elaborate on why this is not the usual approach to the problem (although it isn't particularly harmful either).

The documentation

As supporting evidence for the res.locals approach being the appropriate one for the case, the now outdated documentation is cited:

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

Note the framing here: res.locals is for variables only available "to the view(s) rendered during that request" (emphasis added).

That is what res.locals relates to. res.render renders some template file with some given data as well as access to the locals. This was actually more clear in the v2 docs, and we've now updated the current Express documentation to be clearer:

Use this property to set variables accessible in templates rendered with res.render. The variables set on res.locals are available within a single request-response cycle, and will not be shared between requests.

In order to keep local variables for use in template rendering between requests, use app.locals instead.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.

(Emphasis added.)

The guide

Further evidence of extending req being the standard approach is found in the guide on Writing Middleware, which states:

Next, we’ll create a middleware function called “requestTime” and add a property called requestTime to the request object.

const requestTime = function (req, res, next) {
 req.requestTime = Date.now()
 next()
}

When this was mentioned in discussion in the answers on this here question, one user responded: "This was the way you'd do it before they added res.locals so might be old docs. res.locals is a namespace specifically for this."

This doesn't track with the history of the codebase, however: locals have been present since v2, which is significantly before e.g. express.json was included in the library, at which point it would have made sense to change the behvaior, if it was indeed correct to save values in res.locals.

Closing notes

Shoutout to @real_ate who wrote in the comments, but was overlooked.

Niels Abildgaard
  • 2,662
  • 3
  • 24
  • 32
  • People please consider using `res.local.xxx` as mentioned in other answers. Of course you can do this way also, it is javascript after all. But you may not want to pollute the `req` or `res` object. The libraries use `req.xxx` to make them look legit and ease of use bc the use case is simple and all introduced variables are documented as part of the framework. Real life SW is not always like that. Unless you are developing a framework, just follow the guidelines and save the source code maintain cost. – Han Jun 28 '23 at 00:15
8

That's because req and res are two different objects.

You need to look for the property on the same object you added it to.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
7

The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling

app.get('some/url/endpoint', middleware1, middleware2);

Since you can handle your request in the first middleware

(req, res, next) => {
    var yourvalue = anyvalue
}

In middleware 1 you handle your logic and store your value like below:

req.anyvariable = yourvalue

In middleware 2 you can catch this value from middleware 1 doing the following:

(req, res, next) => {
    var storedvalue = req.yourvalue
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Codedreamer
  • 1,552
  • 15
  • 13
1

As mentioned above, res.locals is a good (recommended) way to do this. See here for a quick tutorial on how to do this in Express.

nax3t
  • 117
  • 4
  • 4
  • 50
  • 1
    Just to be clear, the video doesn't show a solution to what is being asked. The question is about how to pass values from one middleware to another. The video explicitly states that `res.locals` is for passing values straight to template rendering. (But it's a fine video) – Niels Abildgaard Mar 16 '22 at 11:59
0

From https://expressjs.com/en/guide/writing-middleware.html :

const requestTime = function (req, res, next) {
  req.requestTime = Date.now()
  next()
}
p galiardi
  • 139
  • 1
  • 4