⚛️ Next.js Architecture: The React Framework
Standard React (Create React App or Vite) is a Client-Side Rendering (CSR) library.
When a user visits a pure React app, the Node.js server sends them a completely blank index.html file and a massive 2MB bundle.js file. The user stares at a white screen for 3 seconds while their phone downloads and executes the JavaScript to finally draw the UI.
The fatal flaw of CSR: Search Engine bots (like Google) often refuse to wait for JS to execute. They see a blank HTML file and rank your website at #10,000,000 on Google Search.
Next.js by Vercel solves this by moving React rendering back to the server.
1️⃣ Server-Side Rendering (SSR) & Static Site Generation (SSG)
Next.js gives you superpowers. You can mathematically define where and when a React component is executed.
SSR (Server-Side Rendering)
When the user requests /dashboard, the Next.js Node server instantly executes the React components in the cloud, fetches the database, generates a complete 100% finished HTML string, and sends that fully-formed HTML to the browser.
- Pros: Flawless SEO. No loading spinners. The user sees data instantly.
- Cons: The server burns CPU calculating the HTML on every single page load.
SSG (Static Site Generation)
If you build a Marketing Blog, the posts don't change every second. Next.js can read your Markdown files at Build Time, generate 5,000 permanent .html files, and push them to a global CDN.
- Pros: Astronomically fast. It's just a raw HTML file. Costs $0 to host.
- Cons: If you fix a typo in a blog post, you must rebuild and redeploy the entire website.
2️⃣ The App Router Architecture (React Server Components)
In 2023, Next.js 13 introduced the App Router and React Server Components (RSC), revolutionizing the industry.
By default, every single component in the app/ directory is a Server Component.
- It runs exclusively on the server.
- It can communicate directly with PostgreSQL.
import { db } from 'db'. - It ships zero kilobytes of JavaScript to the browser. It only sends the finished HTML!
// app/users/page.tsx
// ⚠️ This component NEVER touches the user's browser. It only runs in AWS/Vercel!
import { db } from '@/database';
export default async function UsersPage() {
// 1. Direct database access right inside React! Unimaginable in standard React.
const users = await db.users.findMany();
return (
<main>
<h1>System Users</h1>
<ul>
{users.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
</main>
);
}
The Problem with Server Components
Server components cannot have interactivity. You cannot use onClick, useState, or useEffect on the server!
To build an interactive button, you must explicitly declare a Client Component using the "use client" directive at the top of the file.
// app/components/LikeButton.tsx
"use client"; // ⚠️ Warning: This component will be downloaded and executed by the Browser!
import { useState } from 'react';
export default function LikeButton() {
const [likes, setLikes] = useState(0);
return <button onClick={() => setLikes(l => l + 1)}>❤️ {likes}</button>;
}
3️⃣ File-System Based Routing
You no longer npm install react-router-dom. Next.js uses folders on your hard drive to create the URLs!
app/
├── page.tsx # Renders http://localhost:3000/
├── about/
│ └── page.tsx # Renders http://localhost:3000/about
├── dashboard/
│ ├── layout.tsx # A wrapper Sidebar specifically for the dashboard
│ └── page.tsx # Renders http://localhost:3000/dashboard
├── blog/
│ └── [slug]/ # The brackets signify a Dynamic Route Variable!
│ └── page.tsx # Renders http://localhost:3000/blog/how-to-code
Dynamic Parameters
// app/blog/[slug]/page.tsx
export default async function BlogPostPage({ params }) {
// 1. Next.js automatically extracts the variable from the folder name!
const title = params.slug; // "how-to-code"
// 2. We use it to fetch the data on the server
const postData = await fetchPostFromDB(title);
return <h1>{postData.title}</h1>;
}
4️⃣ Server Actions (RIP Express APIs?)
Historically, if a React component wanted to update a database, you had to:
- Write a
POSTRoute in an Express.js server. - Ensure CORS is configured.
- Write an
axios.postrequest in React.
Next.js 14 introduced Server Actions. You can write raw server code directly inside your React file, and Next.js creates the invisible API routes for you behind the scenes.
// app/actions/userActions.ts
"use server"; // ⚠️ This explicitly marks these functions to run on the Backend.
import { db } from '@/database';
export async function deleteUser(userId: string) {
if (!verifyAdmin()) throw new Error("Forbidden");
await db.users.delete(userId);
}
// app/users/DeleteButton.tsx
"use client";
// We import the Server function directly into the Client component!
import { deleteUser } from '../actions/userActions';
export default function DeleteButton({ id }) {
return (
// When clicked, Next.js silently fires an invisible HTTP POST request to execute the action!
<button onClick={() => deleteUser(id)}>
Delete Database User
</button>
);
}
💡 Summary Synergy
| Concept | Explanation | Rule of Thumb |
|---|---|---|
| RSC | React Server Component. | Default in Next.js. Flawless SEO, zero JS shipped, direct DB access. |
"use client" | Tells Next.js to ship this file to the browser. | Use ONLY when you need onClick, useState, or useEffect. |
| File Routing | Folders = URLs. page.tsx is the UI. layout.tsx is the wrapper shell. | Makes managing 500 routes incredibly clean. |
| Server Actions | "use server" functions exported for clients. | Replaces the need for writing 90% of basic REST APIs in Express. |