question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Middleware for responses

See original GitHub issue

Similar to how express works there doesn’t seem to be an easy way for an itty middleware to trigger after the response. For express there’s the https://www.npmjs.com/package/express-mung library to mitigate this, but it’s not the most pretty solution. It would be nice if a middleware could be passed a next function that you could await that could return the response object, so something like this:

async function middleware(request, next) {
  const response = await next();

  console.log(response.status);
}

This would make it possible to do things like error handler middlewares, logging response and keeping track of response times.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:14 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
kwhitleycommented, Apr 20, 2022

Here is what I do. Not ideal, but works. Having real middlewares would be awesome.

I mean, by its definition, middleware is simply anything that operates in the middle (in this case of a request and the eventual response/return). Any handler is technically middleware, the same as in Express. The only things differentiating itty’s middleware from Express middleware is:

  • Express requires an explicit next() call to continue to the next handler, vs itty that simply continues the handler chain until something returns. Both have pros/cons. I chose the itty flow because I opt for brevity/simplicity over explicit calls, and the end code gets to look much cleaner as a result. It makes it slightly more difficult to incrementally “assemble” a response, as a consequence.
  • Express passes both the request/response by default through the chain. This encourages you to assemble the response as you go through the middleware/handler chain. You could also do this with itty very easily by just passing in a Response (or more ideally some Response-like object that can construct a Response at the very end) after the request. The only thing itty expects is that the first param to any handler is a Request-like object. That’s it. Want to more closely match an Express param pattern? You can!
import { ResponseMaker } from './somewhere'

// all handlers take the arguments you pass to the handle, in that order... so it's easy to change things up
const middleware = (req, res) => {
  res.status(400) // let's pretend this is how we modify the response-like object
}

const router = Router()

router
  .all('*', middleware)
  .get('/foo', (req, res) => {
    // res.status === 400 from the middleware
        
    return res.json({ error: 'Bad Request' }) // let's pretend this returns a JSON Response
  })
  .get('*', (req, res) => res.status(404).end())

// we change the default signature of handlers this easily...
export default {
  fetch: (req, ...other) => router.handle(req, new ResponseMaker(), ...other)
}
1reaction
markusahlstrandcommented, Jan 23, 2022

Thanks for the reply!

The use case I have right now is that I would like to log the responses to a S3 firehose, which I think should work fine with doing a then/catch on the handler like you showed above. It would be nifty to be able to use middlewares like in koa-router, but for the time being it’s not something I need.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Writing middleware for use in Express apps
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next...
Read more >
Intercepting RESTful Responses with Middleware
An article discussing the application of HTTP middleware to control server responses that would otherwise be influenced by third-party APIs.
Read more >
ASP.NET Core Middleware | Microsoft Learn
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:.
Read more >
Middleware - FastAPI
A "middleware" is a function that works with every request before it is processed by any specific path operation. And also with every...
Read more >
Using Middleware in .NET 5.0 to Log Requests and Responses
Imagine a "pipeline" connecting the client to the server. Middleware sits in that pipe, between client and server, and has the ability to ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found