Search code examples
javascriptnode.jsexpressresponse

Can res.locals be accessed by the api caller?


Currently working on an app where I authenticate and set the auth properties of a user in a middleware (to be used in the route). These auth properties are stored in res.locals.user.

I was wondering if the api caller could access and log the res.locals variable after the request is sent back. From what I've read it doesn't seem like the case but I want to be sure.

I've seen answers refer to the request/response lifecycle so any resource on that would also be greatly appreciated.

Thank you


Solution

  • res.locals.user is local to your server and local to the code processing that specific request. The sender of an incoming http request has no access to that data.

    If you want to share anything in that with the sender of an incoming http request, then you can write your code to include something from there in the response you are sending back as the http response or if you are using an html template engine, then you can code the template to include anything you want from res.locals.user.

    Server-side variables are only available on the server unless your code specifically sends them back to the client. And, things in the req or res object are only available to that specific request while it is being processed. Once the request processing is over and your code for processing the request is done, then those specific req and res objects will be garbage collected and they are not reachable from other requests.