Next.js Discord

Discord Forum

How do I do the equivalent of getStaticProps in app router?

Unanswered
Tan posted this in #help-forum
Open in Discord
TanOP
I've been able to use generateStaticParams to create routes at build time, how do I populate my pages with data at build time and create a partly static site?

9 Replies

You've to fetch data in server component, pass to client component
// app/posts/[id]/page.tsx

// Function to fetch data
async function getPostData(id: string) {
  const res = await fetch(`https://api.example.com/posts/${id}`, {
    cache: 'force-cache', // Ensures data is fetched at build time
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return res.json();
}

export default async function PostPage({ params }: { params: { id: string } }) {
  const data = await getPostData(params.id);

  return (
   // Optionally pass to client component
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  );
}

// Static parameters generation for static paths
export async function generateStaticParams() {
  // Fetch and return the static paths
  return [
    { id: '1' },
    { id: '2' },
    { id: '3' },
  ];
}
@Tan resolved?
TanOP
haven't tried it yet
but makes sense to me
Sun bear
whether its static or not generally depends on whether you import the headers or cookies functions on the page and what the cache on your fetch call is. Next will try to make things static as much as possible but switches to dynamic if the page requires request-specific data (from headers or cookies) or needs some data from a fetch that isnt cached
@Tan but makes sense to me
If it works, mark solution
@Tan ?