Next.js Discord

Discord Forum

How should I set up global redirects?(app directory)

Unanswered
Cuvier’s Dwarf Caiman posted this in #help-forum
Open in Discord
Cuvier’s Dwarf CaimanOP
I basically need the following code to run at the root layout.tsx, but for some reason that doesn't work and I can only add this in page.tsx.

I've tried adding a provider but that doesn't work either...
What's the recommended way of doing this in nextjs 13?

6 Replies

then use that function either, at middleware if it doesnt work, you can reuse that in every page.tsx
Why Middleware might not work properly?:
it is run at a different environment (Edge) than your normal server rendering environment hence some fucntion might not work
also, you might need to change the code a bit to make sure you redirect the request properly.

Why at every page?:
since when navigating between links, soft navigation happens.
Soft navigation means that only the route segment that changed will be processed.
That means if you put your auth guard at parent layout.tsx, it won't be triggered again until you refresh the page.
Cuvier’s Dwarf CaimanOP
So how does middleware work exactly?
is it on the serverside?

ie. when the server receives a request it runs the middleware?
it seems that the middleware can't call DB, but if it's on the server side shouldn't it be able to?
right yea, it seems that every page is the only solution here?

is that the best way to go about that?
seems a little redundant.
Golden-winged Warbler
yeah, there are some less then ideal design choices in middleware and serverside routing, especially with the way we are supposed to do apis in next