Next.js Discord

Discord Forum

Help with data-fetching pattern!

Unanswered
archer posted this in #help-forum
Open in Discord
Hello chat,

I call my API in my middleware.ts file to redirect the user if they're not signed in. My API returns the user object if they are signed in, but this goes to waste as I am not sure how to pass that object to my routes so I call the API again on the client to get the data. I really really want to be able to just call it once in the middleware and pass the returned user to my routes so I don't have to call the API twice per request.

In Express and SvelteKit they have a solution for this where you can attach anything to the request object directly, so I could attach the user object to the request and then access it via the request in my routes, this is done using the request.locals api. I'm throwing that out there to see if maybe someone knows anything similar in NextJS.

If anyone can tell me how to pass data from the middleware to the rest of my app please bless me 🙏

Thanks y'all

0 Replies