0
0
NextJSframework~15 mins

What can run in server components in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - What can run in server components
What is it?
Server components in Next.js are special React components that run only on the server. They can fetch data, access the file system, and perform server-side logic before sending the rendered HTML to the browser. Unlike client components, they do not include any JavaScript for the browser, making pages faster and lighter.
Why it matters
Server components solve the problem of slow page loads caused by heavy JavaScript running in the browser. Without them, every user must download and run all code, even parts that only need server access. This leads to slower experiences and more data usage. Server components let developers run code where it makes the most sense, improving speed and user experience.
Where it fits
Before learning server components, you should understand React basics and client components. After mastering server components, you can explore advanced data fetching, server actions, and full-stack React patterns in Next.js.
Mental Model
Core Idea
Server components run only on the server to prepare HTML and data, sending a lightweight page to the browser without extra JavaScript.
Think of it like...
It's like a chef preparing a meal in the kitchen (server) and only sending the finished dish (HTML) to the customer, instead of sending raw ingredients and recipe steps (JavaScript) for them to cook.
┌─────────────────────┐       ┌─────────────────────┐
│  Server Components   │──────▶│  Rendered HTML sent  │
│  (runs on server)    │       │  to browser client  │
└─────────────────────┘       └─────────────────────┘
           ▲
           │
┌─────────────────────┐
│  Server-only tasks   │
│  (data fetch, fs)   │
└─────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Server Components Basics
🤔
Concept: Server components run only on the server and do not send JavaScript to the browser.
Server components are React components that execute on the server during page rendering. They can fetch data or access server resources directly. The browser receives only the final HTML, so no extra JavaScript is needed for these parts.
Result
Pages load faster because less JavaScript is sent and run in the browser.
Knowing that server components do not send JavaScript to the client helps understand why they improve performance.
2
FoundationWhat Code Can Run in Server Components
🤔
Concept: Server components can run any code that works on the server, including data fetching and file system access.
You can write code inside server components that fetches data from databases, reads files, or calls APIs securely. This code never runs in the browser, so you can use Node.js features safely.
Result
You can securely access sensitive data and resources without exposing them to users.
Understanding that server components can run server-only code unlocks powerful backend capabilities inside React.
3
IntermediateLimitations: No Browser APIs in Server Components
🤔Before reading on: do you think server components can use browser-only features like window or document? Commit to yes or no.
Concept: Server components cannot use browser-specific APIs because they run on the server, not in the browser.
Since server components run on the server, they do not have access to browser objects like window, document, or localStorage. Trying to use these will cause errors.
Result
You must avoid browser-only code in server components and move it to client components.
Knowing this prevents runtime errors and helps decide which code belongs in server vs client components.
4
IntermediateCombining Server and Client Components
🤔Before reading on: do you think server components can handle user interactions like clicks? Commit to yes or no.
Concept: Server components handle data and rendering, while client components handle interactivity and browser APIs.
You can nest client components inside server components. The server component prepares data and HTML, and the client component adds interactivity like buttons or forms that respond to user actions.
Result
You get fast pages with rich interactivity by mixing server and client components.
Understanding this division helps architect apps that are both fast and interactive.
5
AdvancedServer Components and Streaming Rendering
🤔Before reading on: do you think server components can send partial HTML to the browser before full data loads? Commit to yes or no.
Concept: Server components support streaming HTML to the browser as data becomes ready, improving perceived speed.
Next.js streams server component HTML progressively, so users see parts of the page quickly while other parts load. This reduces waiting time and improves user experience.
Result
Pages feel faster because content appears incrementally instead of all at once.
Knowing about streaming helps understand how server components improve real-world performance beyond just code location.
6
ExpertServer Components Internals and Caching
🤔Before reading on: do you think server components re-run all code on every request? Commit to yes or no.
Concept: Server components use caching and deduplication to avoid unnecessary work and speed up rendering.
Next.js caches server component results and shares data between components to reduce repeated fetches or computations. This caching happens automatically and improves scalability.
Result
Server components render faster under load and reduce server resource use.
Understanding caching internals explains why server components scale well and how to optimize data fetching.
Under the Hood
Server components run on the Node.js server during the rendering phase. They execute React code that can access server resources like databases or file systems. The React server renderer converts the component tree into HTML and a special serialized format describing client components. This HTML and data are streamed to the browser, which hydrates client components for interactivity. Server components never send JavaScript to the client, reducing bundle size.
Why designed this way?
Server components were designed to solve the problem of heavy client-side JavaScript and slow page loads. By moving data fetching and rendering to the server, they reduce client work and improve performance. The separation between server and client components allows developers to write code where it makes the most sense, balancing speed and interactivity. Alternatives like full client rendering or traditional SSR either send too much JavaScript or lack interactivity.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Server Code   │──────▶│ React Server  │──────▶│ HTML + Data   │
│ (data fetch,  │       │ Renderer      │       │ Stream to     │
│ file system)  │       │               │       │ Browser       │
└───────────────┘       └───────────────┘       └───────────────┘
                                                      │
                                                      ▼
                                            ┌─────────────────┐
                                            │ Browser Client  │
                                            │ Hydrates Client │
                                            │ Components     │
                                            └─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can server components use browser APIs like localStorage? Commit to yes or no.
Common Belief:Server components can use any JavaScript, including browser APIs like localStorage or window.
Tap to reveal reality
Reality:Server components run on the server and do not have access to browser APIs. Using them causes errors.
Why it matters:Trying to use browser APIs in server components breaks the app and confuses developers about where code runs.
Quick: Do server components send JavaScript code to the browser? Commit to yes or no.
Common Belief:Server components send JavaScript to the browser just like client components.
Tap to reveal reality
Reality:Server components only send HTML and data, no JavaScript is sent for them.
Why it matters:Misunderstanding this leads to overloading the client with unnecessary code and losing performance benefits.
Quick: Do server components handle user events like clicks directly? Commit to yes or no.
Common Belief:Server components can handle user interactions like clicks or form inputs.
Tap to reveal reality
Reality:User interactions must be handled by client components because server components do not run in the browser.
Why it matters:Confusing this causes broken interactivity and poor user experience.
Quick: Do server components always re-run all code on every request? Commit to yes or no.
Common Belief:Server components run fresh on every request without caching.
Tap to reveal reality
Reality:Next.js caches server component results to improve performance and reduce server load.
Why it matters:Ignoring caching can lead to inefficient data fetching and slower apps.
Expert Zone
1
Server components can be nested deeply and still only send minimal HTML, optimizing bandwidth.
2
Automatic caching in server components can be customized with cache-control headers for fine-grained performance tuning.
3
Server components can import client components but not vice versa, enforcing a clear separation of concerns.
When NOT to use
Avoid server components when you need immediate client-side interactivity or access to browser APIs. Use client components or hybrid approaches instead. Also, for very dynamic UI that changes without server round-trips, client components are better.
Production Patterns
In production, server components are used to fetch data securely from databases or APIs, render static parts of pages, and reduce client bundle size. Client components handle forms, animations, and event handlers. Streaming server components improve perceived load times on large pages.
Connections
Microservices Architecture
Both separate concerns by location: server components run on backend servers, microservices split backend logic into services.
Understanding server components helps grasp how splitting responsibilities improves scalability and maintainability, similar to microservices.
Lazy Loading in Web Development
Server components enable partial loading of page content, similar to lazy loading resources on demand.
Knowing server components' streaming helps understand how lazy loading improves user experience by reducing initial load.
Cooking and Meal Preparation
Server components prepare the meal (HTML) in the kitchen (server), client components serve and customize it at the table (browser).
This cross-domain view clarifies the division of labor between server and client in web apps.
Common Pitfalls
#1Trying to use browser-only APIs inside server components.
Wrong approach:export default function MyComponent() { console.log(window.location.href); return
Hello
; }
Correct approach:export default function MyComponent() { return
Hello
; } // Use window.location.href inside a client component instead
Root cause:Misunderstanding that server components run on the server where browser APIs do not exist.
#2Handling user events like clicks directly in server components.
Wrong approach:export default function Button() { function handleClick() { alert('Clicked!'); } return ; }
Correct approach:'use client'; export default function Button() { function handleClick() { alert('Clicked!'); } return ; }
Root cause:Not marking the component as client to enable browser event handling.
#3Expecting server components to send JavaScript to the browser.
Wrong approach:Assuming server components bundle JavaScript for client use and trying to debug client-side errors there.
Correct approach:Recognize server components only send HTML and data; client components handle JavaScript and interactivity.
Root cause:Confusing server rendering with client-side JavaScript execution.
Key Takeaways
Server components run only on the server and send only HTML and data to the browser, improving performance.
They can safely use server-only features like data fetching and file system access, which client components cannot.
Browser APIs and user interactions must be handled in client components, not server components.
Next.js streams server component HTML progressively and caches results to speed up rendering and reduce server load.
Understanding the clear separation between server and client components helps build fast, scalable, and interactive web apps.