Next.js: It's possible to get next.js request object globally?

Created on 21 May 2019  路  2Comments  路  Source: vercel/next.js

I am using fastify with next.js and I need to include tracing (requestId is the problem so far). What I am doing right now is creating a fastify onRequest hook and generating a requestId value and setting it in request object (could be as a request header as well). What I want is to get access to this request object for two reasons:

  1. In logger object (pino in this case, I want to include the requestId in all custom server-side logs).
  2. In all request that needs to be made to other services need to include the requestId in headers.
    Maybe I am missing something trivial and I'm not doing it the best way.

HERE SOME SNIPPETS

This how I am generating the reqId

const fastify = fastifyFactory({
  logger, // logger configuration (Pino instance with custom configuration)
  genReqId: () => {
    return Math.random()
      .toString(36)
      .slice(-6);
  }
});

This is a plugin to gets the reqId generated and setting it to a query property within request object

const tracing = function tracing(fastify, opt, next) {
  fastify.addHook('onRequest', (req, res, nextRequest) => {
    const { id } = req;
    const logger = fastify.log.child({ reqId: id });
    req.query.reqId = id;
    fastify.log = logger; //overrides the current fastify logger to include the reqId in all custom logs
    nextRequest();
  });
  next();
};
tracing[Symbol.for('skip-override')] = true;
module.exports = tracing;

I have no problem when using fastify.log.info(...) because how logger is overrided in each request, it will include the reqId as a child log. The problem is that I want to create a generic logger to use at any part and fastify logger is not available in React components (for example to write logs at getInitialProps). Another important think is tha I need to include this reqId in all request I send to other services (ex: when fetching data), this is why I tried to store this value in request object but need to get it.

All 2 comments

I'm doing something similar to expose my app version. Maybe this could help.

In server.js:

    // inject the app version
    server.use((req, res, next) => {
      req.appVersion = appVersion;
      return next();
    });

the in _app.js I can inject that to the initial props:

class MainApp extends App {
// ...
  static async getInitialProps({ Component, ctx }) {
    const isServer = typeof window === 'undefined';
    let pageProps = {};
    if (isServer) {
      pageProps.appVersion = req.appVersion;
    }
    if (Component.getInitialProps) {
      let compAsyncProps = await Component.getInitialProps(ctx);
      pageProps = { ...pageProps, ...compAsyncProps };
    }
    return { pageProps };
  }
// ...
}

Closing this as the above user provided a viable solution.

Was this page helpful?
0 / 5 - 0 ratings