Topic 25 of 39
Dynamic Rendering
Overview
Dynamic Rendering (SSR) renders the route on the server for every single request. It is automatically triggered in Next.js when you use dynamic functions (like cookies() or headers()) or use cache: 'no-store' in a fetch call.
Syntax
tsx
import { cookies } from 'next/headers';
export default async function Dashboard() {
// Using cookies() automatically opts this route into Dynamic Rendering
const cookieStore = cookies();
const theme = cookieStore.get('theme');
// Fetches fresh data on every request
const userData = await fetch('https://api.com/user', { cache: 'no-store' });
return <div>Welcome back! Your theme is {theme?.value}</div>;
}Common Pitfalls
- Accidentally opting a fully static page into dynamic rendering by importing and using
headers()orcookies(). - Slow database queries on dynamic pages directly impact the user's load time since they wait for the server to respond.
Interview Questions
Q:
What causes a route to switch from Static to Dynamic rendering in Next.js?
A:
Using dynamic functions like cookies(), headers(), or searchParams, OR making an uncached data request (fetch(url, { cache: 'no-store' })).
Real-World Example
A personalized user dashboard that requires reading session cookies and fetching live data.
example
tsx
// A shopping cart page must be dynamic to show the specific user's items
import { cookies } from 'next/headers';
export default function Cart() {
const session = cookies().get('session_id');
// Fetch cart based on session...
}Check Your Knowledge
Test your understanding of Dynamic Rendering with these quick questions.