Discussion

Get and set request-scoped context anywhere in Express app

We may need to store user information to somewhere and want to grab the information from a utility function. Assuming I need to get current logged user and use it in mongoose schema functions.

Using express-http-context npm package, you can easily implement this.

import httpContext from 'express-http-context';

app.use(httpContext.middleware);
app.use((req, res, next) => {
  httpContext.ns.bindEmitter( req );
  httpContext.ns.set('request', req);
  next();
});

In where you want to grab the information;

import httpContext from 'express-http-context';

const req = httpContext.get('request');
this.request = req.requestId || null;

If you want to store user object, you can set user like below.

app.use((req, res, next) => {
  httpContext.ns.bindEmitter( req );
  httpContext.ns.set('request', req);
  httpContext.ns.set('user', req.user);
  next();
});

You can grab these information anywhere in the project.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *