0
0
NextJSframework~5 mins

When to keep components on server in NextJS

Choose your learning style9 modes available
Introduction

Keeping components on the server helps your app load faster and keeps data safe. It means the server does the work, and the user gets ready-to-see pages quickly.

When you want to show content that does not change often, like a blog post or product page.
When you need to keep sensitive data hidden from the user's browser.
When you want faster initial page loads by sending fully built pages from the server.
When SEO (search engine optimization) is important, so search engines can read your content easily.
When your component depends on server-only resources like databases or secret keys.
Syntax
NextJS
export default function Page() {
  // This is a server component by default in Next.js 13+
  return <h1>Hello from the server!</h1>;
}

In Next.js 13+, components inside the app/ folder are server components by default.

You do not need to add special code to make a component run on the server.

Examples
A simple server component that renders a paragraph.
NextJS
export default function ServerComponent() {
  return <p>This runs on the server only.</p>;
}
Adding "use client"; at the top makes this a client component instead.
NextJS
"use client";

export default function ClientComponent() {
  return <button>Click me</button>;
}
Server components can fetch data directly from APIs or databases before rendering.
NextJS
export default async function ServerComponent() {
  const data = await fetch('https://api.example.com/data');
  const json = await data.json();
  return <pre>{JSON.stringify(json, null, 2)}</pre>;
}
Sample Program

This server component checks the current time on the server and shows a greeting. It runs on the server, so the user sees the correct greeting immediately.

NextJS
export default async function ServerGreeting() {
  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Good morning' : 'Good afternoon';
  return <h1>{greeting}, visitor!</h1>;
}
OutputSuccess
Important Notes

Server components cannot use browser-only features like window or document.

Use client components only when you need interactivity like buttons or forms.

Server components help keep your app fast and secure by doing work before sending pages to users.

Summary

Server components run on the server and send ready HTML to the browser.

Use them for static content, data fetching, and security.

Client components are for interactive parts that need the browser.