Next.js course ยท Module 5: Rendering Strategies
Partial Prerendering (PPR)
In this lesson11
In previous modules, we discussed various rendering strategies in Next.js, including data streaming and implementing loading states. In this module, we will focus on one of the newest and most exciting Next.js features - Partial Prerendering (PPR), which combines the advantages of static generation and dynamic rendering in a single hybrid approach.
What Is Partial Prerendering?
Partial Prerendering (PPR) is a rendering pattern introduced in Next.js 14 that allows statically generating parts of a page during the build, while other parts can be dynamically rendered during the request.
Simply put, PPR allows for:
- Instant rendering of static parts of the page (e.g., layout, template, headers)
- Deferred rendering of dynamic parts that require fresh data
Such a hybrid architecture combines the best of both worlds: the speed of static generation with the freshness of dynamic rendering.
Problems That Partial Prerendering Solves
Before PPR was introduced, developers had to choose between several approaches, each with its own limitations:
- Static Site Generation (SSG) - fast content delivery, but problems with data freshness
- Server-Side Rendering (SSR) - always fresh data, but slower TTFB (Time To First Byte)
- Incremental Static Regeneration (ISR) - a compromise between SSG and SSR, but with time-based limitations
- Client-Side Rendering (CSR) - interactivity at the cost of SEO performance
PPR aims to solve these problems by introducing a new hybrid model where these approaches can coexist on a single page in a more integrated way.
How Does Partial Prerendering Work?
PPR introduces a new rendering unit - "holes" or "slots" that are placed in statically generated content. These holes are later filled with dynamically rendered content on the client side.
This process can be divided into four stages:
- Static prerendering - during the build, Next.js generates a static HTML Shell with "holes" for dynamic parts
- Instant response - when a user requests the page, the server immediately responds with the prerendered Shell content
- Dynamic filling - "holes" are asynchronously filled with dynamic data on the server
- Content streaming - dynamic content is streamed to the browser as it's rendered
Implementing Partial Prerendering in Next.js
1. PPR Configuration in Next.js
In Next.js 16, PPR is part of Cache Components, and you enable it with a single option in the next.config.ts file:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;With this option on, PPR works on every route: everything that can be rendered at build time goes into the static shell, including data from functions marked with the 'use cache' directive, while dynamic parts wrapped in <Suspense> stream in at request time. In Next.js 14 and 15, PPR was experimental (in Next.js 15 only in canary releases) and was enabled with the experimental.ppr flag, which Next.js 16 removed:
// next.config.js - Next.js 14-15, this flag no longer works in Next.js 16
module.exports = {
experimental: {
ppr: true
}
}In those versions you could also enable PPR only for selected routes with the experimental_ppr export (with ppr: 'incremental'). Next.js 16 removed this export as well, and with cacheComponents enabled, segment options such as dynamic, dynamicParams, revalidate and fetchCache are no longer available:
// Next.js 15 canary (removed in Next.js 16)
export const experimental_ppr = true;2. Basic PPR Example
Here is an example of PPR implementation in Next.js 16 (with cacheComponents enabled):
// app/products/[category]/page.tsx
import { Suspense } from 'react';
import { cacheLife } from 'next/cache';
import { CategoryHeader } from '@/components/category-header';
import { ProductGrid } from '@/components/product-grid';
import { ProductFilters } from '@/components/product-filters';
import { LoadingSkeleton } from '@/components/loading-skeleton';
// Static parameters for prerendered pages
export async function generateStaticParams() {
const categories = await fetchTopCategories();
return categories.map(category => ({ category: category.slug }));
}
// Static data known at build time
async function getCategoryData(categorySlug: string) {
'use cache';
cacheLife('days');
// Fetch basic category data that rarely changes.
// Thanks to 'use cache' this data is fetched during the build
// and becomes part of the static Shell
const data = await fetch(`https://api.example.com/categories/${categorySlug}`);
return data.json();
}
export default async function CategoryPage({
params,
searchParams,
}: {
params: Promise<{ category: string }>;
searchParams: Promise<Record<string, string>>;
}) {
// Fetch static category data (rendered during build)
const categoryData = await getCategoryData((await params).category);
return (
<div className="container mx-auto py-8">
{/* Statically rendered header - part of the Shell */}
<CategoryHeader category={categoryData} />
<div className="grid grid-cols-4 gap-6 mt-8">
<div className="col-span-1">
{/* Dynamically rendered filters with session-dependent data */}
<Suspense fallback={<LoadingSkeleton type="filters" />}>
<ProductFilters categorySlug={(await params).category} />
</Suspense>
</div>
<div className="col-span-3">
{/* Dynamically rendered product list with fresh data */}
<Suspense fallback={<LoadingSkeleton type="products" />}>
<ProductGrid categorySlug={(await params).category} searchParams={searchParams} />
</Suspense>
</div>
</div>
</div>
);
}In the ProductFilters and ProductGrid components, we will use the cache: 'no-store' option to ensure that data is always fresh:
// components/product-grid.tsx
async function getProducts(categorySlug: string, filterParams?: Record<string, string>) {
// Create URL with filter parameters
const queryParams = new URLSearchParams(filterParams);
const url = `https://api.example.com/products?category=${categorySlug}&${queryParams}`;
// Use no-store option to always fetch fresh data
const res = await fetch(url, { cache: 'no-store' });
if (!res.ok) {
throw new Error('Failed to fetch products');
}
return res.json();
}
export async function ProductGrid({
categorySlug,
searchParams,
}: {
categorySlug: string;
searchParams: Promise<Record<string, string>>;
}) {
// We read the URL filter parameters only here, inside <Suspense>
const filterParams = await searchParams;
// Fetch products with filters applied
const products = await getProducts(categorySlug, filterParams);
return (
<div className="grid grid-cols-3 gap-4">
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}Note that searchParams reaches ProductGrid as a Promise and is read only inside the <Suspense> boundary. This keeps the category header and the loading skeletons in the static shell, and only the product list is dynamic. You cannot use the useSearchParams hook here at all, because it works only in Client Components.
Advanced PPR Patterns
1. Avoiding Data Waterfalls with a Preloader
One of the problems of asynchronous rendering is the "data waterfall," which we can minimize with preloading:
// app/products/[category]/page.tsx
import { Suspense } from 'react';
import { ProductGrid } from './product-grid';
// Preloader function that initiates data loading
function preloadProducts(categorySlug: string) {
// Initiates data fetching but doesn't wait for the result
void getProducts(categorySlug);
}
export default async function CategoryPage({ params }: { params: Promise<{ category: string }> }) {
// Start loading data early
preloadProducts((await params).category);
return (
<div>
{/* Statically prerendered header */}
<h1>Category: {(await params).category}</h1>
{/* Dynamic part */}
<Suspense fallback={<div>Loading products...</div>}>
<ProductGrid categorySlug={(await params).category} />
</Suspense>
</div>
);
}
// Here's what the getProducts function looks like in this case
async function getProducts(categorySlug: string) {
// Function with result caching
// You can use SWR or React Query for more advanced caching
const cacheKey = `products-${categorySlug}`;
if (!cache.has(cacheKey)) {
const promise = fetch(`https://api.example.com/products?category=${categorySlug}`, {
cache: 'no-store'
}).then(res => res.json());
cache.set(cacheKey, promise);
}
return cache.get(cacheKey);
}2. Setting Section Loading Priority
We can set the loading priority of different page parts using nested Suspense components:
// app/dashboard/page.tsx
import { Suspense } from 'react';
import { Header } from '@/components/header';
import { UserWidget } from '@/components/user-widget';
import { RecentActivity } from '@/components/recent-activity';
import { PerformanceMetrics } from '@/components/performance-metrics';
import { Recommendations } from '@/components/recommendations';
import {
UserWidgetSkeleton,
RecentActivitySkeleton,
PerformanceMetricsSkeleton,
RecommendationsSkeleton
} from '@/components/skeletons';
export default function DashboardPage() {
return (
<div className="container mx-auto py-8">
{/* Static part - header */}
<Header title="Dashboard" />
<div className="grid grid-cols-12 gap-6 mt-8">
{/* Priority 1: User widget - loaded first */}
<div className="col-span-3">
<Suspense fallback={<UserWidgetSkeleton />}>
<UserWidget />
</Suspense>
</div>
<div className="col-span-9">
{/* Priority 2: Recent activity - loaded second */}
<Suspense fallback={<RecentActivitySkeleton />}>
<RecentActivity />
<div className="grid grid-cols-2 gap-6 mt-6">
{/* Priority 3: Performance metrics - loaded third */}
<Suspense fallback={<PerformanceMetricsSkeleton />}>
<PerformanceMetrics />
</Suspense>
{/* Priority 4: Recommendations - loaded last */}
<Suspense fallback={<RecommendationsSkeleton />}>
<Recommendations />
</Suspense>
</div>
</Suspense>
</div>
</div>
</div>
);
}3. Dynamic Parameters with Partial Prerendering
We can combine static generation and dynamic parameters:
// app/products/[id]/page.tsx
import { Suspense } from 'react';
// We only statically generate specific product pages
export async function generateStaticParams() {
// Fetch only popular products for prerendering
const popularProducts = await fetchPopularProducts();
return popularProducts.map(product => ({
id: product.id.toString()
}));
}
// With dynamicParams: true enabled, products without static generation
// will be rendered on demand
export const dynamicParams = true;
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
// This function fetches basic product information
// For popular products, this data will be fetched during build
// For the rest - during the request
const product = await getProductBasicInfo((await params).id);
if (!product) {
return <div>Product not found</div>;
}
return (
<div className="product-page">
<h1>{product.name}</h1>
<div className="product-image">
<img src={product.imageUrl} alt={product.name} />
</div>
<div className="product-info">
<p className="product-price">${product.price}</p>
{/* Dynamic part with always up-to-date information */}
<Suspense fallback={<div>Checking availability...</div>}>
<ProductAvailability productId={(await params).id} />
</Suspense>
<Suspense fallback={<div>Loading delivery options...</div>}>
<DeliveryOptions productId={(await params).id} />
</Suspense>
</div>
<div className="product-details">
{/* Static part - product description */}
<div dangerouslySetInnerHTML={{ __html: product.description }} />
{/* Dynamic part - reviews, frequently updated */}
<Suspense fallback={<div>Loading reviews...</div>}>
<ProductReviews productId={(await params).id} />
</Suspense>
</div>
</div>
);
}
async function getProductBasicInfo(id: string) {
// Fetching basic product information
// Can be cached since this information rarely changes
const res = await fetch(`https://api.example.com/products/${id}/basic`);
if (!res.ok) return null;
return res.json();
}4. Dynamic Routing with Partial Prerendering
We can also use PPR with dynamic routes, e.g., for advanced filtering:
// app/products/[[...slug]]/page.tsx
import { Suspense } from 'react';
// Generate popular filter/category combinations for prerendering
export async function generateStaticParams() {
return [
{ slug: [] }, // /products
{ slug: ['category', 'electronics'] }, // /products/category/electronics
{ slug: ['deals'] }, // /products/deals
// ... other popular combinations
];
}
export const dynamicParams = true; // Allows dynamic rendering of other combinations
export default async function ProductsPage({ params }: { params: Promise<{ slug?: string[] }> }) {
// Parsing slug parameters
const { category, filters } = parseSlug((await params).slug || []);
// Fetching static metadata
const pageMetadata = await getPageMetadata(category);
return (
<div className="container mx-auto py-8">
{/* Static part - header and metadata */}
<h1>{pageMetadata.title}</h1>
<p>{pageMetadata.description}</p>
<div className="flex mt-8">
{/* Dynamic part - filters */}
<div className="w-1/4">
<Suspense fallback={<div>Loading filters...</div>}>
<ProductFilters category={category} activeFilters={filters} />
</Suspense>
</div>
{/* Dynamic part - product list */}
<div className="w-3/4">
<Suspense fallback={<div>Loading products...</div>}>
<ProductList category={category} filters={filters} />
</Suspense>
</div>
</div>
</div>
);
}
// Helper function for parsing slug parameters
function parseSlug(slug: string[]) {
let category = '';
const filters: Record<string, string> = {};
for (let i = 0; i < slug.length; i += 2) {
if (slug[i] === 'category' && slug[i+1]) {
category = slug[i+1];
} else if (slug[i] && slug[i+1]) {
filters[slug[i]] = slug[i+1];
}
}
return { category, filters };
}Data Caching in PPR
Optimal data caching is crucial for PPR performance. Here are some caching patterns:
1. React-level Caching
// utils/cache.ts
export const dataCache = new Map();
export async function getCachedData(key: string, fetcher: () => Promise<any>) {
if (!dataCache.has(key)) {
try {
const promise = fetcher();
dataCache.set(key, promise);
const data = await promise;
return data;
} catch (error) {
dataCache.delete(key);
throw error;
}
}
return dataCache.get(key);
}Usage:
// components/product-list.tsx
import { getCachedData } from '@/utils/cache';
async function getProducts(category: string) {
return getCachedData(`products-${category}`, () => {
return fetch(`https://api.example.com/products?category=${category}`, {
cache: 'no-store'
}).then(res => res.json());
});
}2. Memoization of Data Fetching Functions
// lib/fetch-client.ts
import { cache } from 'react';
// Using React memoization to cache query results
export const fetchAPI = cache(async (url: string, options: RequestInit = {}) => {
const res = await fetch(url, options);
if (!res.ok) {
throw new Error(`Failed to fetch ${url}`);
}
return res.json();
});Usage:
// components/product-data.tsx
import { fetchAPI } from '@/lib/fetch-client';
export async function ProductData({ id }: { id: string }) {
// The query will be executed only once per render,
// even if the component is used multiple times with the same id
const product = await fetchAPI(`https://api.example.com/products/${id}`);
return (
<div className="product-data">
<h2>{product.name}</h2>
<p>{product.description}</p>
<p className="price">${product.price}</p>
</div>
);
}PPR Usage Examples in Different Scenarios
1. E-commerce
PPR is ideal for e-commerce product pages where we can:
- Prerender static elements: product name, images, description, specifications
- Dynamically render: stock status, promotional prices, customer reviews
2. Information Portals
For information websites, PPR allows:
- Prerendering the page template, article headers, and static sections
- Dynamically rendering personalized recommendations and latest news
3. Application Dashboards
For analytical dashboards:
- Prerendering the dashboard structure, controls, and user interface
- Dynamically rendering charts and user-specific analytical data
Debugging and Monitoring PPR
Debugging PPR can be challenging due to the hybrid nature of rendering. Here are some tips:
1. Using React DevTools
React DevTools allows inspecting components and their rendering state.
2. Debugging Static Generation
NEXT_DEBUG=1 next buildThis command shows detailed information about which pages are generated statically.
3. Production Environment Monitoring
Implement performance monitoring tools such as Lighthouse, PageSpeed Insights, or Core Web Vitals monitoring tools to evaluate the impact of PPR on the end-user experience.
Limitations and Considerations
- Experimental feature - PPR is still an experimental feature and may change
- Supported environments - PPR works best with Node.js and edge runtime
- Mental model complexity - the hybrid rendering model can be harder to understand and debug
- Optimal usage - PPR is not always the best choice; for simple static pages, SSG may be simpler and more efficient
Best Practices
1. Balancing Static vs. Dynamic Content
Clearly define which data can be rendered statically and which must be dynamic:
- Static: user interface, constant metadata, rarely updated content
- Dynamic: personalized data, frequently updated information, user context-dependent data
2. Loading Prioritization
Use nested Suspense to prioritize content loading:
- Load business-critical data first
- Less important sections can be loaded later
3. Efficient Cache Management
Carefully manage data caching to avoid unnecessary re-renders:
- Use
fetchAPIwith React memoization - Apply cache validation using revalidatePath and revalidateTag
4. Appropriate Loading Skeletons
Design loading skeletons that match the dimensions and proportions of the final content to minimize layout shifts.
Summary
Partial Prerendering (PPR) is a powerful Next.js feature that enables combining the performance of static generation with the flexibility of dynamic rendering. It allows creating fast, interactive applications with optimal performance for different content types.
The main benefits of PPR are:
- Faster TTFB - static parts are delivered instantly
- Better SEO performance - critical content is statically prerendered
- Optimal user experience - a stable template minimizes flickering during dynamic content loading
- Flexibility - easy combination of different rendering strategies in a single application
Although PPR is still in an experimental phase, it offers an exciting vision of the future of rendering in Next.js, combining the advantages of previously dispersed approaches to generating web content.
In the next module, we will discuss cache management in detail and advanced data revalidation techniques that are crucial for the optimal operation of PPR and other rendering strategies in Next.js.
Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';
// Partial Prerendering (PPR) - simulation in Next.js
// The static part is rendered immediately, the dynamic part is streamed later
function StaticShell() {
return (
<div style={{ background: '#1a2744', borderRadius: 8, padding: 16, border: '1px solid #64ffda' }}>
<h3 style={{ color: '#64ffda', margin: 0 }}>Static shell (prerendered)</h3>
<p style={{ color: '#aaa', fontSize: 13, margin: '8px 0 0' }}>
Navigation, layout and metadata are available immediately.
This part of the page is generated at build time.
</p>
</div>
);
}
function DynamicSection({ label, delay }: { label: string; delay: number }) {
const [data, setData] = useState<string | null>(null);
useEffect(() => {
const t = setTimeout(() => setData(`Dynamic data: ${label} (loaded after ${delay}ms)`), delay);
return () => clearTimeout(t);
}, [label, delay]);
if (!data) {
return (
<div style={{ background: '#0d1117', borderRadius: 8, padding: 16, border: '1px dashed #555' }}>
<div style={{ color: '#888', fontSize: 13 }}>Streaming: {label}...</div>
<div style={{
height: 10, background: 'linear-gradient(90deg, #333, #555, #333)',
backgroundSize: '200% 100%', borderRadius: 4, marginTop: 8,
animation: 'shimmer 1.5s ease-in-out infinite'
}} />
</div>
);
}
return (
<div style={{ background: '#1b5e20', borderRadius: 8, padding: 16, border: '1px solid #4caf50' }}>
<div style={{ color: '#4caf50', fontWeight: 'bold', fontSize: 13 }}>DYNAMIC</div>
<div style={{ color: '#e0e0e0', marginTop: 4 }}>{data}</div>
</div>
);
}
export default function PPRDemo() {
const [key, setKey] = useState(0);
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<style>{`@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }`}</style>
<h1 style={{ color: '#64ffda' }}>Partial Prerendering (PPR)</h1>
<p style={{ color: '#888' }}>
The static shell loads immediately, dynamic sections stream independently.
</p>
<button onClick={() => setKey(k => k + 1)} style={{
background: '#9c27b0', color: '#fff', border: 'none', borderRadius: 6,
padding: '8px 16px', cursor: 'pointer', margin: '12px 0', fontFamily: 'monospace'
}}>
Simulate reload
</button>
<div key={key} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<StaticShell />
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<DynamicSection label="User cart" delay={800} />
<DynamicSection label="Recommendations" delay={2000} />
</div>
<DynamicSection label="Community comments" delay={3000} />
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Streaming in Next.js allows:
2. Suspense boundaries in React are used for:
Hands-on tasks in the game
- Code editor
Create loading.tsx and error.tsx components for graceful handling of loading and error states
- Vertical ordering
Arrange the ISR (Incremental Static Regeneration) revalidation stages in correct order:
- Click in order
Arrange the generateStaticParams function syntax in Next.js
- Code editor
Create an application combining Server Components (header, footer) with Client Components (interactive form)