0
0
NextJSframework~5 mins

Server component restrictions in NextJS

Choose your learning style9 modes available
Introduction

Server components run only on the server to keep your app fast and secure. They cannot use browser-only features.

When fetching data directly from a database or API without exposing secrets.
When rendering static content that does not need user interaction.
When you want to keep sensitive logic hidden from the browser.
When you want to improve performance by reducing client-side JavaScript.
When you want to separate server logic from client UI code.
Syntax
NextJS
export default function MyServerComponent() {
  // Server-only code here
  return <div>Hello from server</div>;
}

Server components cannot use hooks like useState or useEffect.

They cannot access browser APIs like window or document.

Examples
Fetching data directly on the server and rendering it.
NextJS
export default async function ServerComponent() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  return <pre>{JSON.stringify(data)}</pre>;
}
Trying to use browser API 'window' in server component causes error.
NextJS
export default function ServerComponent() {
  // This will cause an error
  // console.log(window.location.href);
  return <div>Cannot use window here</div>;
}
Sample Program

This server component fetches a todo item from an API and renders it. It runs only on the server, so it can safely fetch data without exposing API keys or secrets.

NextJS
import React from 'react';

export default async function ServerComponent() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const todo = await res.json();

  return (
    <main>
      <h1>Todo Item</h1>
      <p><strong>Title:</strong> {todo.title}</p>
      <p><strong>Completed:</strong> {todo.completed ? 'Yes' : 'No'}</p>
    </main>
  );
}
OutputSuccess
Important Notes

Server components cannot use React hooks that depend on the browser.

They can import other server components or client components.

Use client components when you need interactivity or browser APIs.

Summary

Server components run only on the server and cannot use browser features.

They are great for data fetching and rendering static content securely.

Use client components for interactive UI and browser-dependent code.