Next.js Discord

Discord Forum

Access request and response object with app router

Unanswered
American black bear posted this in #help-forum
Open in Discord
Avatar
American black bearOP
How do I access the request object when using the app router (and the response object as well, for sending headers and such)?

Previously, getServerSideProps would let me view the incoming request and modify the response accordingly, before any real processing has begun. I'd like to implement ratelimits (and have different ratelimits for different "categories" of pages), and I'm struggling to find a good way to do this with app router.

I see that I can use middleware, but having access to only one middleware file makes this a bit clunky: my code describing a single page lives in multiple files, and I have to implement route matching myself. The alternative seems to be using middleware to extract details that I need into fake headers, then read those "headers" in my server components, but I really don't like that approach.

I'm also looking to access session data (account ID, etc.) in my server components. Previously, I've been calling express-session (which probably isn't the best approach in the world--and if anyone has any suggestions for changing this up, I'll take them--but I use to have my frontend and backend share session data) on the request and response objects, but this doesn't seem viable anymore, for the aforementioned reasons. It also might be difficult sticking session data into a "header", and I'd really want to avoid un-needed serialization/deserialization.

In any case, if anyone has any ideas on how I can access request/response objects, or how I can implement this through some other mechanism, I'd really appreciate it!

1 Reply

Avatar
American black bearOP
Related to https://nextjs-forum.com/post/1118640528020475944. It seems like running server-specific code, completely disentangled from client code, just isn't something that app router can do. I love a lot of the things (including a lot of the paradigm shift) that come from app router, but lacking a good way to have fine-grained control over the HTTP side of things just makes it unreasonably difficult to do certain things, especially ones that really have nothing to do with React (e.g. ratelimiting).