0
0
NextJSframework~5 mins

What can run in server components in NextJS

Choose your learning style9 modes available
Introduction

Server components run code 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 from a database securely without exposing credentials to the browser.
When you need to run code that uses Node.js APIs not available in the browser.
When you want to generate HTML on the server to improve page load speed.
When you want to keep sensitive logic hidden from users.
When you want to reduce JavaScript sent to the browser for better performance.
Syntax
NextJS
export default async function MyServerComponent() {
  // Server-only code here
  const data = await fetchDataFromDatabase();
  return <div>{data}</div>;
}
Server components run only on the server and never in the browser.
You can use async/await to fetch data directly inside server components.
Examples
Fetch data from an API on the server and display it.
NextJS
export default async function ServerComponent() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  return <div>{data.message}</div>;
}
Use Node.js file system API to read a file on the server.
NextJS
import fs from 'fs';

export default function ReadFile() {
  const content = fs.readFileSync('file.txt', 'utf8');
  return <pre>{content}</pre>;
}
Access environment variables safely on the server.
NextJS
export default function ServerOnlyLogic() {
  const secret = process.env.SECRET_KEY;
  return <div>Secret is hidden from browser</div>;
}
Sample Program

This server component reads a text file on the server and shows its content inside a <pre> block. The file reading happens only on the server, so the browser never sees the file system code.

NextJS
import fs from 'fs';

export default function ServerComponentExample() {
  const data = fs.readFileSync('data.txt', 'utf8');
  return <main>
    <h1>Server Component Example</h1>
    <p>File content:</p>
    <pre>{data}</pre>
  </main>;
}
OutputSuccess
Important Notes

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

They can import and use Node.js modules freely.

Server components can call other server components or client components.

Summary

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

They can safely use server-only code like database access, file system, and environment variables.

This helps improve performance and security by reducing client-side JavaScript.