Next.js Discord

Discord Forum

Redirect From RootLayout or Page?

Answered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
Hello guys.
Which is better, redirect from layout or page? which file is executed first?
// layout.tsx
export default async function RootLayout() {
const session = await getServerSession(authOptions)

if(!session) redirect('/')

...
}

Or
// page.tsx
export default async function Page {
const session = await getServerSession(authOptions)

if(!session) redirect('/')

...
}
Answered by American
for me it's depend if u need redirect for all your page that using that layout put in layout if not put in page.. and fyi u can put it on middleware if u are using next-auth
View full answer

9 Replies

It doesn't matter, it will be a server side redirection anyways and your users won't see any difference.
If you really care do it inside your layout file
American
for me it's depend if u need redirect for all your page that using that layout put in layout if not put in page.. and fyi u can put it on middleware if u are using next-auth
Answer
+ you can also use middleware without next-auth
Asiatic LionOP
Thank you guys 🌟
you should mark a message as solution
@riský *you should mark a message as solution*
Asiatic LionOP
How?
Right click -> Apps -> Mark Solution
Asiatic LionOP
Thank you bro @riský