hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.64k stars 65 forks source link

Running a handler at the end of chain? #170

Closed younanjo closed 2 years ago

younanjo commented 2 years ago

does anyone know if it's possible to have a handler that always runs at the end of the chain? A use-case may be a logger middleware that logs to stdout once all middleware have run. For example if you've got:

function onError(err, req, res, next) {
  ...
}

function logger(req,res) {
    // a Pino logger
}

const baseHandler = nc({ onError })
    .use(auth)
   .use(somethingElse);

// Some API using base handler
baseHandler
  .get("/api/foo", (req, res, next) => {
        // do something here
  });

How do you add logger so that it logs every req/req as part of the middleware chain but ran last? I don't want to make every get/post/put... responsible for its own logging. How are you peeps doing it?

lluio commented 2 years ago

I haven't figured out a way to do this, either, but would be interested in this functionality. in Gin for Golang any code run after calling next in a middleware is run after next has completed. A solution might be to do the same here. I.e.

nc<NextApiRequest, NextApiResponse>({})
    .use(async (req, res, next) => {
      console.log("I'm run before the main GET function");
      next();
      console.log("I'm run after the main GET function");
    })
    .get((req, res) => {
      res.status(200).json({ yes: "Yes!" });
    });
hoangvvo commented 2 years ago

This seems to model the flow like in koa, in which case, is not currently supported because next-connect models after connect/express. There is a PR to address this pattern https://github.com/hoangvvo/next-connect/pull/148. I will give it some thought in the next several days whether we should switch over to that (unlikely because of breakability) or add it as an "extra".

younanjo commented 2 years ago

@hoangvvo any thoughts on supporting such a feature? If not, would you be able to suggest a pattern on how one would about logging req/res ?

hoangvvo commented 2 years ago

@hoangvvo any thoughts on supporting such a feature? If not, would you be able to suggest a pattern on how one would about logging req/res ?

Did you try the morgan middleware? https://github.com/expressjs/morgan