41. SSR & Frameworks (Next.js)
The Problem with Standard React
React is inherently a Client-Side Rendering (CSR) library. When a user visits a standard React app, the server sends a completely blank HTML file (<div id="root"></div>) and a massive JavaScript file. The browser has to download the JS, execute it, and then finally draw the UI. This results in slow initial load times on mobile devices and terrible SEO, because search engine crawlers often just see a blank white page. Next.js solves this by moving rendering back to the Server.
Server-Side Rendering (SSR) vs Static Site Generation (SSG)
Next.js allows you to pre-render your React components into actual, fully populated HTML before sending them over the network to the browser.
- SSR: The HTML is generated dynamically on the server every single time a user requests the page. This is best for highly dynamic data that changes constantly (like a user's banking dashboard or shopping cart).
- SSG: The HTML is generated only once during build time (when you deploy the site to production). That static HTML file is then cached and reused for every visitor. This is insanely fast and perfect for marketing pages, documentation, or blogs.
The Next.js App Router
Next.js drastically simplifies routing. You don't need `react-router-dom`. The physical file system is the router. Creating a folder named about with a page.tsx file inside automatically creates the /about URL for your website.
React Server Components (RSC)
By default, all components in the Next.js App Router are Server Components. They execute exclusively on the backend server and ship ZERO JavaScript logic to the browser. This means they can securely connect directly to databases without exposing API keys!
Client Components
Server Components are great for performance, but they have no access to the browser window. They cannot use useState, onClick, or useEffect. If you need interactivity (like a button that tracks clicks or opens a modal), you must explicitly mark the component as a Client Component using the 'use client' directive at the very top of the file.
SEO Optimization (Metadata)
Because Next.js renders on the server, injecting SEO tags is trivial. You simply export a metadata object from any page.tsx or layout.tsx file.
Knowledge Check
Ready to test your understanding of 41. SSR & Frameworks (Next.js)?