Next.js Discord

Discord Forum

Layout args

Answered
deathlybower959 posted this in #help-forum
Open in Discord
Avatar
I have a layout which governs protected authenticated routes, and the function returns some basic user data. I would like to pass this data to all children components of this layout.

How would I do so cleanly?
Answered by B33fb0n3
your layout shouldn't handle authenticated routes. Data can be leaked. If you want to fix this, follow this advice: https://github.com/eric-burel/securing-rsc-layout-leak

TL;DR:
checking authentication in a middleware
checking authentication in the page
checking authentication in the data fetching method

After you done that, you can easily pass the data around via props. For example you secure your route by fetching it in your page.tsx:
// ...

const data = await fetchData();

return <>
  <RenderThisData data={data} />
</>

// ...
View full answer

5 Replies

Avatar
@deathlybower959 I have a layout which governs protected authenticated routes, and the function returns some basic user data. I would like to pass this data to all children components of this layout. How would I do so cleanly?
Avatar
your layout shouldn't handle authenticated routes. Data can be leaked. If you want to fix this, follow this advice: https://github.com/eric-burel/securing-rsc-layout-leak

TL;DR:
checking authentication in a middleware
checking authentication in the page
checking authentication in the data fetching method

After you done that, you can easily pass the data around via props. For example you secure your route by fetching it in your page.tsx:
// ...

const data = await fetchData();

return <>
  <RenderThisData data={data} />
</>

// ...
Answer
Avatar
import { NextPage } from "next";
import ProductsGrid from "@/components/products/ProductsGrid";
import client from "@/lib/apollo/apolloClient";
import { GET_PRODUCTS_PREVIEW } from "@/lib/graphql/queries";
const HomePage: NextPage = async () => {
  let data = null;

  try {
    const response = await client.query({
      query: GET_PRODUCTS_PREVIEW,
    });
    data = response.data;
    console.log("Data fetched successfully:", data);
  } catch (error: any) {
    console.error(
      "GraphQL query error:",
      error.networkError?.result || error.message,
    );
  }

  return data ? (
    <ProductsGrid items={data.productsCollection.items} />
  ) : (
    <p>Loading products...</p>
  );
};

export default HomePage;
 
 



i want to pass the fetched data to ProductsGrid component but this aint working and i think i know why is that, maybe because its a server component and it has no way of tracking state and rerendring based on that, there is no state going on and using regualar let variable aint going to work, but chatGPT gave me this code tho, so how to fix this? it keeps showing "Loading products..."