Next.js Discord

Discord Forum

Server action execute even if page is not being rendered

Answered
Ankit posted this in #help-forum
Open in Discord
I have a custom AuthProvider component which conditionally renders children only if the necessary permissions and access is validated
But the page is still being executed even if the children is not being rendered, leading to errors which i urgently need to handle

The page is a server component which makes a couple of api calls which needs to be called only if the access is valid, but now since the apis are being called even if not being rendered it causes issue

Dummy Code:
layout.tsx
import "./globals.css";

export default function RootLayout() {
    return (
        <html lang="en">
            <body>
            </body>
        </html>
    );
}


page.tsx
import { fetchData } from "./actions";

const Home = async () =>{  
    const data = await fetchData();
    return (
        <div className="">{data}</div>
    );
}

export default Home;
Answered by joulev
pages and layouts are run in parallel, independently from each other. pages are still run, regardless of whatever is in the layout.

only when they finish, would nextjs combine them into a html tree to send to the browser. this is where your layout not having a children makes a difference.

so the way to fix here is to fix your page. make it no longer fail.
View full answer

12 Replies

Longtail tuna
ur Home page is rendered, i believe it doesnt matter what u do in RootLayout in this case
but the page should only be rendered if children is used right, becoz there this no ui being displayed and not even found in devtools elements tab
Longtail tuna
its not sent to user, but still gets rendered in server.
any way to avoid that? or unless i change the way the Home renders same thing will happen
Longtail tuna
maybe some conditional render
becoz whats happening is the apis use cookies() from next/headers there when i try to find the cookies it returns null leading to the issue
Longtail tuna
then id check cookies before calling fetchData
but then i will have to keep doing this on each page and api, any other optimal way?
Longtail tuna
depends what u trying to achieve i guess
got it thanks
Answer
Thanks for the explanation