โฒNext.js, SSR/CSR & Caching
12.1SSR vs CSR (and the rest of the spectrum)
| Aspect | SSR (Server-Side Rendering) | CSR (Client-Side Rendering) |
|---|---|---|
| Where HTML is built | On the server, per request | In the browser, after JS loads |
| Initial load | Slower TTFB, faster first content | Fast TTFB (minimal HTML), slower first content |
| SEO | Excellent (crawlers see full HTML) | Weaker (needs JS execution / prerender) |
| Time to Interactive | Delayed by hydration | Depends on bundle size |
| Server cost/complexity | Higher (Node server per request) | Lower (static host + API) |
| Best for | Public, SEO-critical, content pages | Internal tools, dashboards, SPAs behind auth |
The fuller spectrum you should name:
- CSR โ ship JS, render in browser.
- SSR โ render HTML per request on the server.
- SSG (Static Site Generation) โ render to HTML at build time; serve static files. Fastest, cheapest; content fixed until rebuild.
- ISR (Incremental Static Regeneration) โ SSG + background revalidation. Static speed with periodic freshness.
- RSC (React Server Components) โ see 14.1. The modern App Router default; components that run only on the server and ship zero JS.
Hydration = React attaching event listeners and state to the server-rendered HTML on the client. Until hydration completes, the page looks ready but isn't interactive. Large bundles โ long hydration โ poor INP.
12.2Optimizing Next.js SSR + caching (layered)
1. ISR โ the workhorse. Static performance with periodic updates:
// App Router
export const revalidate = 3600; // regenerate at most once/hour
export async function generateStaticParams() { /* pre-render known paths */ }
// Pages Router
export async function getStaticProps() {
return { props: { /* ... */ }, revalidate: 3600 };
}
2. Fetch-level caching (App Router extends fetch):
const data = await fetch(url, { next: { revalidate: 60 } }).then(r => r.json());
// or cache: 'force-cache' | 'no-store' for full control
3. On-demand revalidation โ regenerate the moment content changes (CMS webhook), instead of waiting for the timer:
// App Router: revalidatePath('/blog/[slug]') or revalidateTag('posts')
// Pages Router: await res.revalidate('/blog/my-post')
4. Edge/CDN caching via Cache-Control:
Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400
// s-maxage: CDN caches 1h; SWR: serve stale up to 24h while revalidating in background
5. Database/data caching (Redis) for expensive queries, with explicit invalidation on write. Use a read-through cache wrapper: check Redis โ miss โ query DB โ store โ return; on update, del the key.
Route-strategy classification:
- Static, rarely changes (
/about) โ SSG, revalidate daily - Dynamic but not real-time (
/blog/[slug]) โ ISR, revalidate hourly - CMS-driven (
/products/[id]) โ ISR + on-demand revalidation - User-specific/auth (
/dashboard) โ SSR + client cache (react-query) - Real-time (
/live) โ CSR / streaming / websockets
12.3Environment variables & secrets (Q15 โ critical to get right)
- Anything sent to the browser is public. In Next.js, only vars prefixed
NEXT_PUBLIC_are exposed to client code; they're embedded in the bundle at build time. Never put secrets there. - Build-time public config (
NEXT_PUBLIC_API_URL) โ fine, it's meant to be visible. - Runtime secrets (API keys, DB URLs, tokens) โ server-only. Read them in server code (route handlers, server components,
getServerSideProps). They never reach the client. - The pattern for third-party secrets: browser โ your backend โ third-party API with the secret. The secret lives only on your server.
- Never commit
.envfiles; use the platform's secret manager (Vercel env vars, AWS Secrets Manager, etc.) in production.
// Client-safe (exposed intentionally)
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
// Server-only (never bundled to client)
const dbUrl = process.env.DATABASE_URL; // only readable server-side
๐ง Quiz: Next.js, SSR/CSR & Caching
2 questions1In Next.js, which environment variables are exposed to the browser?
2SSR (server-side rendering) primarily improves: