0
0
NextJSframework~5 mins

Zero bundle size for server components in NextJS

Choose your learning style9 modes available
Introduction

Server components let you run code only on the server, so your web page sends less code to the browser. This makes your app faster and smaller.

When you want to fetch data securely without exposing API keys to the browser.
When you want to keep heavy logic or libraries only on the server to reduce client load.
When you want to improve page load speed by sending less JavaScript to the user.
When you want to separate UI parts that don't need interactivity from those that do.
When you want to build SEO-friendly pages with server-rendered content.
Syntax
NextJS
export default function MyServerComponent() {
  // This code runs only on the server
  return <div>Hello from server!</div>;
}

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

They do not include client-side JavaScript in the browser bundle.

Examples
A simple server component that renders a paragraph.
NextJS
export default function ServerComponent() {
  return <p>Rendered on server only</p>;
}
Server component can fetch data securely on the server before rendering.
NextJS
import { fetchData } from '@/lib/data';

export default async function ServerComponent() {
  const data = await fetchData();
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Client components include "use client" directive and run in the browser.
NextJS
"use client";

export default function ClientComponent() {
  return <button>Click me</button>;
}
Sample Program

This server component fetches a user name on the server and renders a greeting. No JavaScript for this component is sent to the browser, so the page loads faster.

NextJS
import React from 'react';

// This is a server component
export default async function Greeting() {
  // Simulate fetching user name on server
  const userName = await Promise.resolve('Alice');

  return (
    <main>
      <h1>Hello, {userName}!</h1>
      <p>This text is rendered on the server only.</p>
    </main>
  );
}
OutputSuccess
Important Notes

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

They help reduce the JavaScript bundle size sent to the client.

Use client components only when you need interactivity like event handlers.

Summary

Server components run only on the server and send zero JavaScript to the browser.

This reduces bundle size and improves page load speed.

Use server components for static or data-fetching UI parts without interactivity.