Next.js Discord

Discord Forum

Should I call my API in middleware?

Unanswered
Lukas posted this in #help-forum
Open in Discord
Ideally, I want to make my page start to load as fast as possible, so logically, I would assume that a blocking request to the db would be bad. This is actually a waterfall request too, because I call getUser and refresh their auth token.

If I were to call it in a layout, I would be able to cache the request. But, this has downsides too. It's still blocking TTFB while it goes to the db/reads cache, and I would lose out on the benefits of PPR when that becomes stable.

I could also potentially do the permissions check in the components themselves (which are wrapped in suspense).

3 Replies

American Chinchilla
What about server comps?
Doing the fetch there
@American Chinchilla What about server comps?
That's what I meant by the last bit since you won't have the TTFB issues once PPR is stable. That would probably work though, maybe I'll do that? The only thing I can think of is I'll need to make 100% sure I don't forget it for a certain component (yay unit testing). I just wish there was a more ideal way to do this where you could start loading the route and run middleware at the same time