🌐 Web Development

Partial Prerendering

Partial Prerendering

Mixed rendering of static/dynamic content. An experimental feature in Next.js 14+.

πŸ“– Detailed Explanation

Partial Prerendering (PPR) is an experimental rendering strategy introduced in Next.js 14 that serves static content and dynamic content together on a single page. Previously, an entire page was rendered as either SSG (static) or SSR (dynamic), but PPR combines the two in a hybrid approach.

The core idea of PPR is the "Static Shell." Unchanging parts of the page such as the layout, navigation, and header are pre-rendered at build time and cached on a CDN, while dynamic parts such as user information, the shopping cart, and recommended products are filled in by streaming at request time. This achieves both the fast TTFB of static content and the personalization of dynamic content.

Technically, PPR makes use of React's Suspense and streaming. When a dynamic component is wrapped in Suspense, the static shell is sent first, and the dynamic part displays a loading UI and is then replaced by streaming once it is ready. Because this entire process happens within a single HTTP response, it provides a fast user experience without additional round trips.

PPR is particularly useful on e-commerce sites. The images, descriptions, and specs on a product detail page are rendered statically, while stock status, price, and the number of user reviews are fetched dynamically. This allows search engines to crawl the product information, and users can see the latest information in real time.

πŸ’» Code Example

// === next.config.js - PPR ν™œμ„±ν™” ===
/** @type {import('next').NextConfig} */
const nextConfig = {
    experimental: {
        ppr: true, // Partial Prerendering ν™œμ„±ν™”
    },
};

module.exports = nextConfig;

// === app/products/[id]/page.tsx - PPR 적용 νŽ˜μ΄μ§€ ===
import { Suspense } from 'react';
import { ProductInfo } from './ProductInfo';
import { ProductPrice } from './ProductPrice';
import { ProductReviews } from './ProductReviews';
import { RecommendedProducts } from './RecommendedProducts';

// 정적 νŒŒλΌλ―Έν„° 생성 (λΉŒλ“œ μ‹œ)
export async function generateStaticParams() {
    const products = await getProducts();
    return products.map((product) => ({ id: product.id }));
}

// 정적 메타데이터
export async function generateMetadata({ params }: { params: { id: string } }) {
    const product = await getProduct(params.id);
    return {
        title: product.name,
        description: product.description,
    };
}

export default async function ProductPage({ params }: { params: { id: string } }) {
    // 이 데이터 νŽ˜μΉ­μ€ λΉŒλ“œ μ‹œ μ‹€ν–‰ (정적 λΆ€λΆ„)
    const product = await getProduct(params.id);

    return (
        <div className="product-page">
            {/* 정적 λΆ€λΆ„ - λΉŒλ“œ μ‹œ λ Œλ”λ§λ˜μ–΄ CDN에 캐싱 */}
            <header>
                <h1>{product.name}</h1>
                <ProductInfo product={product} />
            </header>

            {/* 동적 λΆ€λΆ„ - μš”μ²­ μ‹œ 슀트리밍 */}
            <Suspense fallback={<PriceSkeleton />}>
                <ProductPrice productId={params.id} />
            </Suspense>

            {/* 정적 λΆ€λΆ„ */}
            <section className="description">
                {product.description}
            </section>

            {/* 동적 λΆ€λΆ„ - μ‚¬μš©μžλ³„ μΆ”μ²œ */}
            <Suspense fallback={<RecommendationsSkeleton />}>
                <RecommendedProducts productId={params.id} />
            </Suspense>

            {/* 동적 λΆ€λΆ„ - μ‹€μ‹œκ°„ 리뷰 */}
            <Suspense fallback={<ReviewsSkeleton />}>
                <ProductReviews productId={params.id} />
            </Suspense>
        </div>
    );
}

// === components/ProductPrice.tsx - 동적 μ»΄ν¬λ„ŒνŠΈ ===
// 이 μ»΄ν¬λ„ŒνŠΈλŠ” cookies() λ˜λŠ” headers()λ₯Ό μ‚¬μš©ν•˜λ―€λ‘œ λ™μ μœΌλ‘œ λ Œλ”λ§
import { cookies } from 'next/headers';

export async function ProductPrice({ productId }: { productId: string }) {
    // cookies()λ₯Ό μ‚¬μš©ν•˜λ©΄ μžλ™μœΌλ‘œ 동적 λ Œλ”λ§μœΌλ‘œ μ „ν™˜
    const userRegion = cookies().get('region')?.value || 'KR';

    // 지역별 가격 쑰회 (μ‹€μ‹œκ°„)
    const pricing = await fetch(
        `https://api.example.com/pricing/${productId}?region=${userRegion}`,
        { cache: 'no-store' } // 동적 데이터
    ).then(res => res.json());

    return (
        <div className="price-section">
            <span className="currency">{pricing.currency}</span>
            <span className="amount">{pricing.amount.toLocaleString()}</span>
            {pricing.discount > 0 && (
                <span className="discount">{pricing.discount}% 할인</span>
            )}
            <StockStatus available={pricing.inStock} />
        </div>
    );
}

// === components/RecommendedProducts.tsx - κ°œμΈν™”λœ μΆ”μ²œ ===
import { headers } from 'next/headers';

export async function RecommendedProducts({ productId }: { productId: string }) {
    // headers()λ₯Ό μ‚¬μš©ν•˜λ©΄ μžλ™μœΌλ‘œ 동적 λ Œλ”λ§
    const headersList = headers();
    const userId = headersList.get('x-user-id');

    const recommendations = await fetch(
        `https://api.example.com/recommendations`,
        {
            method: 'POST',
            body: JSON.stringify({ productId, userId }),
            cache: 'no-store'
        }
    ).then(res => res.json());

    return (
        <section className="recommendations">
            <h2>μΆ”μ²œ μƒν’ˆ</h2>
            <div className="grid">
                {recommendations.map((item: Product) => (
                    <ProductCard key={item.id} product={item} />
                ))}
            </div>
        </section>
    );
}

// === μŠ€μΌˆλ ˆν†€ μ»΄ν¬λ„ŒνŠΈ (λ‘œλ”© μƒνƒœ) ===
function PriceSkeleton() {
    return (
        <div className="price-skeleton animate-pulse">
            <div className="h-8 w-32 bg-gray-700 rounded" />
        </div>
    );
}

function RecommendationsSkeleton() {
    return (
        <section className="recommendations-skeleton">
            <h2>μΆ”μ²œ μƒν’ˆ</h2>
            <div className="grid grid-cols-4 gap-4">
                {[1, 2, 3, 4].map(i => (
                    <div key={i} className="h-48 bg-gray-700 rounded animate-pulse" />
                ))}
            </div>
        </section>
    );
}

πŸ—£οΈ Examples of Practical Conversations

PM

"My product page is built with SSG, but the price and stock need to be shown in real time. Do we have to switch the whole page to SSR?"

Developer

"You can use PPR (Partial Prerendering). Keep the static parts such as product information, images, and descriptions cached as SSG as they are, and just wrap the price and stock in Suspense to stream them dynamically. You can keep TTFB fast while still showing real-time data."

Colleague

"What's the difference between PPR and the existing ISR?"

Developer

"ISR periodically regenerates the entire page, whereas PPR separates the static and dynamic parts within a single page. ISR shows every user the same cached page, but with PPR you can share the static shell while showing personalized dynamic content differently for each user."

Interviewer

"How does Next.js determine which components will be rendered dynamically?"

Candidate

"If you use dynamic functions such as cookies() and headers(), or pass the cache: 'no-store' option to fetch, that component is automatically rendered dynamically. If it is inside a Suspense boundary, only that part is filled in later by streaming, and the parts outside it are pre-rendered statically."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

Experimental feature: PPR is an experimental feature introduced in Next.js 14. Verify its stability before using it in production, and review the changes carefully when upgrading versions.

Suspense boundary: Dynamic components must be wrapped in Suspense for PPR to work properly. If you use a dynamic function without Suspense, the entire page switches to dynamic rendering and you lose the benefits of PPR.

Caching strategy: Static parts are cached on a CDN, so if changes are needed after the build, a redeployment is required. Separate frequently changing content into dynamic components or use it in combination with ISR.

πŸ”— Related Terms

πŸ“š Learn More