Custom middleware after nextjs RequestHandler
See original GitHub issueFeature request
Related to https://github.com/zeit/next.js/issues/6290 We need to run some logic after every route is handled.
Is your feature request related to a problem? Please describe.
We have a Prometheus client where we report performance metrics. “handleRequest” does not call next and therefore our code is never invoked.
Custom Server Example
// Runs before each requests
server.use((req, res, next) => {
res.locals.startEpoch = Date.now();
next();
});
server.get("/", (req, res) => {
return handleRequest(req, res, "/", req.query);
});
server.get("*", (req, res) => {
return handleRequest(req, res);
});
// Runs after each requests - **THIS NEVER GETS INVOKED**
server.use((req, res, next) => {
const responseTimeInMs = Date.now() - res.locals.startEpoch;
httpRequestDurationMicroseconds
.labels(req.method, req.route.path, res.statusCode)
.observe(responseTimeInMs);
next();
});
Describe the solution you’d like
handleRequest should call next This would solve https://github.com/zeit/next.js/issues/7499 as well allowing people to add middlewares
Describe alternatives you’ve considered
I’ve not found a workaround
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (4 by maintainers)
Top Results From Across the Web
Custom middleware after nextjs RequestHandler #7665
We have a Prometheus client where we report performance metrics. "handleRequest" does not call next and therefore our code is never invoked.
Read more >Advanced Features: Middleware
Middleware allows you to run code before a request is completed, then based on the incoming request, you can modify the response by...
Read more >Put custom middleware last in the chain in a custom next.js ...
1 Answer 1 · Well, handle is the request handler of Next. It is not part of my code. · Oh OK, I...
Read more >How to Add Middleware in Next.js API Routes - YouTube
In this video you will learn a framework for writing Next.js middleware so you can do things like protect your API routes from ......
Read more >Writing middleware for use in Express apps
Call the next middleware in the stack. If the current middleware function does not end the request-response cycle, it must call next() to...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Next.js does not provide a middleware, it ends the request when you call handle. So like @janpot is saying you’ll probably want to add on finish or similar.
There already was an open RFC before this issue was posted: https://github.com/zeit/next.js/issues/7208