Short answer: fast Next.js sites aren't the result of one clever trick. They come from three boring decisions enforced in code: prerender everything that doesn't need a session, keep request-time logic (the proxy, formerly middleware) off the pages that don't need it, and never let an unoptimised byte reach public/. On our own site those three decisions took a 214-file portfolio library from 377.7 MB to 64.4 MB (−83.0%). They also left marketing pages served straight from the CDN with zero proxy invocations.
This teardown covers the rebuild of rapidgrowth.agency from a WordPress and Elementor install to the Next.js 16 App Router. It's our own site, so every figure below is measured from the repository and the asset pipeline's run report, not estimated. Where we haven't measured something yet, such as field Core Web Vitals on the new build, we say so.
The challenge: a page builder can't hold a performance budget
The old site was the kind of WordPress install most agencies run: a premium theme, Elementor, a handful of plugins, and a portfolio uploaded straight from design exports. It worked, but nothing in that stack could refuse a slow page. The bottlenecks, in the order they cost us:
- Unbounded media. The portfolio library held 214 files totalling 377.7 MB. Twenty-eight of them were animated GIFs, and those 28 files alone weighed 256.9 MB, 68% of the library. One brand project (25 files) accounted for 175.0 MB by itself.
- Markup weight from the page builder. Elementor wraps each widget in nested containers carrying serialised
data-settingsJSON. Our WordPress export shows a single blog paragraph sitting five<div>s deep. That markup is parsed on every page view, whether the visitor needs it or not. - Request-time work on every page. On a PHP stack every uncached view runs the full application. Caching plugins help, but cache invalidation lives in a plugin's settings screen, not in code review.
- No contract between content and layout. An image with no intrinsic dimensions is a layout shift waiting to happen. WordPress records dimensions at upload, but nothing stops a theme or page builder from dropping them.
The goal for the rebuild was a lab LCP under one second on cached pages and a site that fails the build rather than ship a regression.
The solution: four decisions, each enforced in code
1. Prerender by default with Cache Components
Next.js 16 with cacheComponents: true flips the default: a route is static unless it touches request data (cookies(), headers(), searchParams) outside a cached scope. Data reads opt into caching explicitly with the "use cache" directive and a cacheLife profile, so the cache policy sits next to the query it governs:
// lib/blog-data.ts
export async function getPostSummaries(): Promise<PostSummary[]> {
"use cache";
cacheLife({ revalidate: 3600 });
const supabase = createClient();
const { data: posts, error } = await supabase
.from("posts")
.select("slug, title, excerpt, published_at, content_html")
.eq("type", "post")
.not("published_at", "is", null)
.order("published_at", { ascending: false });
// Throwing fails the build instead of prerendering an empty blog.
if (error) throw new Error(`Failed to load blog posts: ${error.message}`);
return posts.map(toPostSummary);
}
Two details matter more than the directive itself:
- The cache keys on arguments. The listing page, each article and the article's previous/next deck all call the same function, so one revalidation window means one database read, not three.
- Failures throw. A sitemap or listing that silently renders empty when the database hiccups is worse than a failed deploy. Our sitemap throws on any failed query for the same reason.
Dynamic routes pre-render through generateStaticParams. With Cache Components on, it must return at least one param, and an empty array is a build error. That's the behaviour you want: the build proves every slug renders before anything ships.
2. Scope the proxy to the three routes that need a session
"Edge middleware" is the advice most performance guides still give, but Next.js 16 changed the ground under it. middleware.ts is deprecated and renamed to proxy.ts, and the proxy now runs on the Node.js runtime by default. You can't set runtime in a proxy file at all. The Next.js docs also recommend treating it as a last resort.
So the question isn't "edge or Node". It's which requests should run any code at all. On our site the answer is three route patterns:
// proxy.ts
export async function proxy(request: NextRequest) {
// ...createServerClient with request/response cookie adapters...
// getClaims() verifies the JWT signature and refreshes an expired session.
// Never gate on getSession(): it trusts the cookie without verifying it.
const { data } = await supabase.auth.getClaims();
// ...route staff to /crm and clients to /portal...
}
export const config = {
matcher: ["/portal/:path*", "/crm/:path*", "/login"],
};
Every marketing page, blog post and case study falls outside the matcher, so no request-time code runs for them. The proxy only decides which shell a signed-in user should see. Page-level guards (requireStaffRole, getCurrentUser) stay authoritative, so a matcher mistake can't become an authorisation bug.
3. A media pipeline that owns every byte in public/
Nothing reaches public/assets/work/ without passing through scripts/optimize-work-assets.mjs, a sharp-based pipeline:
// scripts/optimize-work-assets.mjs (stills)
const MAX_WIDTH = 1920;
const WEBP_IMAGE = { quality: 80, smartSubsample: true, effort: 6 };
const { data, info } = await sharp(file, { pages: 1 })
.rotate() // bake EXIF orientation in before metadata is stripped
.resize({ width: MAX_WIDTH, withoutEnlargement: true })
.webp(WEBP_IMAGE)
.toBuffer({ resolveWithObject: true });
The rules it enforces:
- Stills: at most 1920px wide, never upscaled, WebP at quality 80 with smart chroma subsampling. EXIF, ICC and XMP are stripped and pixels are converted to sRGB. If the source is already a lean WebP and re-encoding would make it bigger, the original bytes are kept.
- Animations: every GIF gets a first-frame poster (for
prefers-reduced-motionand as the<video>poster), plus either an H.264 MP4 whenffmpegis available or an animated WebP otherwise. Both walk a size ladder (1280px at q70, then q60, then 960px at q60, then q55) toward a 1.5 MB budget. The ladder stops at a quality floor instead of degrading visibly. - Safety: outputs are staged and verified, originals are moved to a git-ignored archive (never deleted), and the staged tree is swapped in at once.
- A typed manifest: the run rewrites
lib/data/portfolio-media.generated.tswith every file'ssrc,width,heightandbytes. Portfolio entries reference media by a key typed askeyof typeof PORTFOLIO_MEDIA. Rename or delete a folder andtscfails, so a broken image can't reach production.
That manifest is what keeps CLS honest: every <Image> on the site receives intrinsic dimensions from generated data, not from a human remembering to type them.
4. Let the CDN and the image optimiser do the rest
// next.config.ts
const nextConfig: NextConfig = {
cacheComponents: true,
images: {
// AVIF first (~20% smaller than WebP at equal quality), WebP fallback.
formats: ["image/avif", "image/webp"],
},
async headers() {
return [
{
// public/assets is not content-hashed: replace a file by renaming it.
source: "/assets/:path*",
headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }],
},
];
},
};
/_next/image then negotiates AVIF or WebP per browser and resizes per srcset breakpoint, so a phone never downloads the 1920px master. The immutable header carries one trade-off you have to respect: files in /assets are not content-hashed, so a changed image needs a new filename. The comment in the config says so, because the next engineer will not read this article.
Measured outcomes
All figures come from the pipeline's run report for 16 November 2026, covering the full portfolio library.
| Slice | Files | Source | Shipped | Reduction |
|---|---|---|---|---|
| Total library | 214 | 377.7 MB | 64.4 MB | −83.0% |
| Animated GIFs | 28 | 256.9 MB | 33.5 MB | −87.0% |
| Still images | 186 | 120.8 MB | 30.9 MB | −74.5% |
| Branding projects | 163 | 307.5 MB | 48.8 MB | −84.1% |
| UI/UX projects | 21 | 63.7 MB | 13.2 MB | −79.3% |
| SaaS & web app projects | 30 | 6.5 MB | 2.4 MB | −63.4% |
Three things in that table are worth reading closely:
- The median still went from 276.6 KB to 84.2 KB. 174 of the 214 sources were already WebP exported from WordPress, and they still shrank by roughly two-thirds. Format alone isn't optimisation. Resizing to a real display width and stripping metadata did most of the work.
- Animations were the whole problem. GIFs were 68% of the source bytes. Converting them saved more than every still combined.
- SaaS projects compressed least (−63.4%) because UI screenshots were already small, flat-colour PNG and WebP exports. Expect a smaller win on interface-heavy portfolios.
What's still open, stated plainly:
- 6 of 28 animations remain above the 1.5 MB budget, the largest at 5.75 MB. This run used the animated-WebP fallback because
ffmpegwasn't installed. Re-running with--sourceagainst the archive andffmpegon the path produces MP4s, which compress motion far better. - We haven't published field Core Web Vitals for the new build yet. Lab numbers on a developer laptop prove little. Google's "good" thresholds are an LCP of 2.5 s or less and an INP of 200 ms or less at the 75th percentile of real visits, and the Chrome UX Report needs a 28-day window to report them. We'll add the CrUX figures to this article once that window closes.
How to apply this to your own Next.js build
- Audit bytes before code. Sum
public/and your CMS uploads by file type. If animations dominate, as ours did, fix those first. - Make the pipeline the only way in. A script that rewrites a typed manifest beats a style guide asking people to compress images.
- Turn on Cache Components and let the build fail loudly. Throw on failed queries and return real params from
generateStaticParams. - Write the proxy matcher as an allow-list. If a route doesn't need a session, it shouldn't run proxy code.
- Ship immutable caching only with a rename rule. Long cache lifetimes are free speed until someone replaces a file in place.
If you're planning a rebuild, our web engineering service runs this process, and the Regulatis case study shows it on a SaaS product.
Frequently asked questions
How do you make a Next.js website load in under one second?
Serve the HTML from a CDN cache rather than rendering per request, and keep the largest image small. In Next.js 16 that means enabling Cache Components, caching data reads with 'use cache' and cacheLife, pre-rendering dynamic routes with generateStaticParams, and keeping the proxy off public pages. Then resize images to their display width, encode them as AVIF or WebP, and give every image intrinsic dimensions so nothing shifts while it loads.
Does Next.js middleware still run on the edge in Next.js 16?
No, not by default. Next.js 16 deprecates middleware.ts and renames it proxy.ts, and the proxy runs on the Node.js runtime by default; setting a runtime option in the proxy file throws an error. The performance win now comes from running the proxy on fewer requests: write its matcher as an allow-list of the routes that need a session, so static pages never execute it.
What image compression settings work best for a Next.js site?
For photographic and design assets, resize to the largest width you display (we use 1920px), encode WebP at quality 80 with smart chroma subsampling, and strip EXIF, ICC and XMP metadata. Let next/image serve AVIF first with WebP as the fallback. Convert animated GIFs to MP4 or animated WebP with a size budget; on our site GIFs were 68% of all source bytes and shrank 87%.


