0
0
NextJSframework~5 mins

Server component execution model in NextJS

Choose your learning style9 modes available
Introduction

Server components run on the server to prepare content before sending it to the browser. This helps make pages faster and lighter.

When you want to fetch data securely from a database without exposing credentials to the browser.
When you want to reduce the amount of JavaScript sent to the user for faster page loads.
When you want to render parts of your page that do not need user interaction on the server.
When you want to improve SEO by sending fully rendered HTML to search engines.
When you want to keep sensitive logic or API keys hidden from the client.
Syntax
NextJS
export default async function MyServerComponent() {
  // Server-only code here
  const data = await fetchDataFromAPI();
  return (
    <div>{data.message}</div>
  );
}

Server components are React components that run only on the server.

They can fetch data directly and do not include client-side JavaScript.

Examples
This server component shows the current time when the page loads.
NextJS
export default function Greeting() {
  const time = new Date().toLocaleTimeString();
  return <p>Current time: {time}</p>;
}
This server component fetches user data before rendering the greeting.
NextJS
export default async function UserProfile() {
  const res = await fetch('https://api.example.com/user');
  const user = await res.json();
  return <h1>Welcome, {user.name}!</h1>;
}
Sample Program

This server component shows the current server time when the page loads. It runs only on the server and sends the rendered HTML to the browser.

NextJS
export default async function ServerTime() {
  const now = new Date().toLocaleString();
  return (
    <main>
      <h1>Server Time</h1>
      <p>The current server time is: {now}</p>
    </main>
  );
}
OutputSuccess
Important Notes

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

They help reduce JavaScript sent to the client, improving performance.

Use server components for static or data-fetching parts of your UI.

Summary

Server components run only on the server and prepare HTML before sending it to the browser.

They improve performance by reducing client-side JavaScript.

Use them to fetch data securely and render static content.