最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you preserve request context in a Node JS App using express? - Stack Overflow

programmeradmin5浏览0评论

My request object contains a unique id which every log in my app must have.This id must also be propagated to any APIs I'm calling from my back-end Right now, I'm passing the request object everywhere. This is obviously not an ideal solution.Are there any suggestions?

CODE FLOW

Client------->Server(generate request id, use this for all logs)----->pass request id to any api call

Code:

app.use(function(req,res,next) {    
  logger.info("My message",req);
});

My request object contains a unique id which every log in my app must have.This id must also be propagated to any APIs I'm calling from my back-end Right now, I'm passing the request object everywhere. This is obviously not an ideal solution.Are there any suggestions?

CODE FLOW

Client------->Server(generate request id, use this for all logs)----->pass request id to any api call

Code:

app.use(function(req,res,next) {    
  logger.info("My message",req);
});
Share Improve this question edited Sep 18, 2015 at 15:40 dm03514 56k18 gold badges117 silver badges147 bronze badges asked Sep 18, 2015 at 15:35 Anurag OjhaAnurag Ojha 1011 gold badge1 silver badge3 bronze badges 4
  • Code is just an example as to how I am passing the request context to my logger – Anurag Ojha Commented Sep 18, 2015 at 15:36
  • 2 If all you need is the request id for logging, how about just passing the request id instead of the whole request object? I imagine it would be a lot more lightweight (i.e. just a number or string) – arcyqwerty Commented Sep 18, 2015 at 15:42
  • Hi, doesn't javascript pass the reference to an object, rather than the object itself?Will it really substantially affect the performance ? Anyway, my main concern here was to avoid passing an extra parameter in a lot of apis and logging calls.Thanks for your time though, appreciate it. – Anurag Ojha Commented Sep 18, 2015 at 18:46
  • Does this answer your question? Access request context anywhere – Juan Perez Commented Feb 28, 2024 at 0:40
Add a ment  | 

3 Answers 3

Reset to default 4

Here is a revised solution using the continuation-local-storage module.

Here is my context module. So far it only stores path, request time and correlation ID that it generates if it doesn’t receive one in the request.

'use strict';

const continuation = require('continuation-local-storage');
const cuid = require('cuid');

const appName = require('config').get('app_name');

class Context {

    static setup(req, res, next) {
        const session = continuation.createNamespace(appName);
        session.run(() => {
            session.set('context', new Context(req));
            next();
        });
    }

    constructor(req) {
        this.path = req.path;
        this.corrId = req.headers['x-correlation-id'] || cuid();
        this.requestTime = Date.now();
    }

    static current() {
        return continuation.getNamespace(appName).get('context');
    }
}

module.exports = Context;

My app.js includes:

const Context = require('./context');

app.use(Context.setup);

After that, any code can call Context.current() to get the current context of the Express request. I will use that for consistent logging.

You can use the continuation-local-storage module. There is also the request-local module that is just a small layer on top of continuation-local-storage. Don't expect continuation-local-storage to always be perfect though...you will run into edge cases where the cls context will be invalid.

Given this is the first link that shows up when I search for "express request context", I thought I'd give a more recent answer. I believe the correct place to store contextual information about a request/response lifecycle is in res.locals as per the Express docs. According to another SO answer, req.locals is also used however there is no mention of this in the docs and the type definitions do not allow for it out of the box.

发布评论

评论列表(0)

  1. 暂无评论