kwhitley / itty-router

A little router.
MIT License
1.78k stars 78 forks source link

Modify response in Middleware #72

Closed MexHigh closed 2 years ago

MexHigh commented 2 years ago

I'm currently trying to modify all responses for all routes to include the Access-Control-Allow-Origin header. Is there any way to do this with middleware?

If not then consider this a feature request :)

kwhitley commented 2 years ago

Currently the way to do this is modify the response AFTER the handle function delivers one. I’ll be adding this pattern to the docs to deal with everyone’s favorite CORS issue, plus adding some helpers to itty-router-extras for dealing with this.

(I’m away from my computer, so bare with me on the unformatted code)

router .handle(request, env) .then(response => { response.headers.set(‘access-control-allow-origin’, ‘*’)

return response

})

Alternative, you could absolutely make some middleware that sets up the Response and embeds it in the Request that’s passed through the router (while building on it in handlers/middleware). A bit more like express in that, albeit unconventional in where it resides. The only catch with that is to remember that the moment you return anything from a handler/middleware, the handle function will be considered resolved (with that value)!

Hope this helps!