0
0
NextJSframework~3 mins

Why Use server directive in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how Server Components can make your Next.js apps faster and easier to build!

The Scenario

Imagine building a web page where you manually fetch data on the server, then pass it down to the client, and finally update the UI. You have to write extra code to handle data fetching, loading states, and errors on the client side.

The Problem

This manual approach is slow and complicated. You write repetitive code for fetching and rendering. It's easy to make mistakes, like fetching data multiple times or showing incomplete UI. Managing server and client code separately becomes confusing.

The Solution

Server Components in Next.js run only on the server by default in the App Router. This means data fetching and rendering happen together on the server, so the client gets ready-to-use HTML. It simplifies your code and improves performance.

Before vs After
Before
export async function getServerSideProps() {
  const data = await fetchData();
  return { props: { data } };
}
function Page({ data }) {
  return <div>{data.title}</div>;
}
After
async function Page() {
  const data = await fetchData();
  return <div>{data.title}</div>;
}
What It Enables

This lets you write simpler, faster components that fetch data and render on the server automatically, giving users instant content without extra client work.

Real Life Example

Think of an online store homepage that shows the latest products. Using Server Components, the page fetches product info on the server and sends fully rendered HTML to the browser instantly, so shoppers see products right away.

Key Takeaways

Manual data fetching and rendering is complex and error-prone.

Server Components simplify by running only on the server.

It improves performance and user experience by sending ready HTML.