Next.jsHard
How do you analyze and fix slow build times in Next.js?
Measure first (build logs show per-phase timings, plus --experimental-cpu-prof and Turbopack traces), then fix the slowest phase: enable and persist Turbopack's filesystem cache in CI, avoid prerendering more pages than needed, speed up data fetching during static generation, separate type checking, and trim heavy dependencies and plugins.
Measure
next buildprints timings for compilation, type checking, collecting page data and generating static pages (with the worker count, 16.1+).next build --experimental-cpu-profwrites CPU profiles to.next-profiles/.- Turbopack tracing (see the local development guide) for compiler hot spots.
--debug-build-paths="app/blog/**"builds a subset to iterate quickly.
Common fixes
- Use Turbopack (default in 16). A custom
webpack()config forces--webpack; port it toturbopackoptions. - Cache between CI runs: persist
.next/cache. Turbopack's filesystem cache for builds is on by default since 16.3 and made CI builds up to 5.5x faster in Vercel's measurements. - Prerender fewer pages at build: return only popular paths from
generateStaticParamsand let the rest generate on demand (ISR or App Shell). - Faster data during prerender: batch or cache CMS requests with
"use cache"; slow APIs multiply across thousands of pages. TunestaticGenerationoptions (concurrency, retries). - Type checking: run
tscin a parallel CI job, or try TypeScript 7 (native, much faster) withuseTypeScriptClisupport (16.3). - Linting no longer runs in
next buildsince 16; run ESLint or Biome separately. - Babel and the React Compiler: the Babel-based compiler slows builds; try
experimental.turbopackRustReactCompiler(16.3+). - Dependencies:
optimizePackageImportsfor barrel packages,serverExternalPackagesfor heavy server-only libraries. - Monorepos: Turborepo remote caching skips unchanged apps entirely.
Code example
tsx
1// next.config.ts2import type { NextConfig } from "next";34const nextConfig: NextConfig = {5 // Persistent Turbopack caches (defaults in recent 16.x, shown for clarity)6 experimental: {7 turbopackFileSystemCacheForBuild: true,8 optimizePackageImports: ["@acme/icons"],9 },10 serverExternalPackages: ["@prisma/client", "sharp"],11};12export default nextConfig;1314// app/blog/[slug]/page.tsx - prerender only the top pages at build time15// export async function generateStaticParams() {16// const top = await getPosts({ orderBy: "views", take: 100 });17// return top.map((p) => ({ slug: p.slug }));18// }1920// CI (GitHub Actions) - keep the cache between runs21// - uses: actions/cache@v422// with: { path: .next/cache, key: next-${{ hashFiles('package-lock.json') }}-${{ github.sha }},23// restore-keys: next-${{ hashFiles('package-lock.json') }}- }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.