Next.js Discord

Discord Forum

Subpage gets rendered/executed on the server even if the root layout does not render any children.

Unanswered
Harlequin Duck posted this in #help-forum
Open in Discord
Harlequin DuckOP
I have a Layout on / , I also have a page at /some-other-route.
My layout has a blocker for unauthenticated users. So if authentication is not given the Layout renders a LoginPage and does not render or include the children at all.

However, I just realised that when I navigate to /some-other-route my page.tsx under /some-other-route actually executes on the server (console logs, executes fetches), even if my RootLayout does not render the children at all.

Why is that?
Does Next.js render from bottom to top or from top to bottom?
Are there common practices for stuff like that? I don't want my subpage to execute on the server if it is not being rendered.


// Layout at /
const Layout = (props) => {
     return (<div>This is a totally empty layout without any children</div>)
}
export default Layout

// page at /some-other-route
const Page = (props) => {
     console.log("This message gets actually logged on the server")
     return (<div>This does not get rendered but still executes on the server when navigating to /some-other-route</div>)
}
export default Page

3 Replies

@Ray yeah, I think its because we may fetch data inside the component. we should use `notFound` or `redirect` on the page if you don't want the page to show or handle it on middleware
Harlequin DuckOP
Aaaa
That's what I feared.
I just have a bunch of pages that I want to render conditionally, which all share a common ancestor Layout.
Having to handle auth in every page itself is going to be a drag :/
Ty tho