Next.js
Beginner
1 min read
Server-Side Rendering and Dynamic Routes
Example
// app/feed/page.tsx — fully dynamic (SSR) page
import { cookies, headers } from 'next/headers';
// Opt this entire route into dynamic rendering
export const dynamic = 'force-dynamic';
async function getFeed(userId: string) {
// no-store = skip cache, always fetch fresh
const res = await fetch(`https://api.example.com/feed/${userId}`, {
cache: 'no-store',
});
if (!res.ok) throw new Error('Failed to load feed');
return res.json();
}
export default async function FeedPage() {
// Reading cookies opts the route into dynamic rendering
const cookieStore = cookies();
const userId = cookieStore.get('userId')?.value;
// Reading headers also opts into dynamic rendering
const headersList = headers();
const userAgent = headersList.get('user-agent') ?? 'unknown';
if (!userId) {
return <p>Please log in to see your feed.</p>;
}
const feed = await getFeed(userId);
return (
<div>
<p className="text-xs text-gray-400">Viewing from: {userAgent}</p>
<ul>
{feed.items.map((item: { id: string; title: string }) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}