Dumb Next question (noob?)

I need to take a piece of data I fetch in my middleware and pass it to my routes and pages. Right now, I fetch the data in my middleware, and then I have to fetch it again in my app. The middleware controls redirects and the app consumes the data. I'll attach a pic for clarity, it's just a user object returned from my API endpoint (it's on a separate server) Ideally I'd like to have the API endpoint be called once in the middleware, then all other times it's called it's either cached or the middleware sends the data from the API directly to the client. In Express, I'd use request.locals for this but idk how to do it in Next.
No description
Solution:
Not sure how your app has the auth implemented but as far as I know Next automaticaly deduplicates fetch requests (fires it only once and then serves it from the cache) and actually recommends to repeat the fetch queries throughout your app code. So if your main goal is to reduce DB calls this takes care of it....
Jump to solution
4 Replies
Alky
Alky•11mo ago
I don't think that using middleware it's possible to pass it as props, but nextjs 13 allows you to access the request Header and Cookies on your pages. So you can set the information as a header and then read it on the page. Since this way you're using a header, you probably need to be a bit careful here, since setting a header for a request is pretty easy to do. That is, create some validation so you know that the header is created by you, not someone else, if you're passing some info that, if forged, could lead to problems.
Solution
Zikado
Zikado•11mo ago
Not sure how your app has the auth implemented but as far as I know Next automaticaly deduplicates fetch requests (fires it only once and then serves it from the cache) and actually recommends to repeat the fetch queries throughout your app code. So if your main goal is to reduce DB calls this takes care of it.
archer
archerOP•11mo ago
This was helpful, thanks!
Zikado
Zikado•11mo ago
Glad it helped 🙂
Want results from more Discord servers?
Add your server