blog
Critical CSS for static Next.js: critters, fonts and the first screen on PSI mobile
My static Next.js site hit 3 PSI mobile traps: render-blocking CSS, inlined fonts loading too early, and JS gating the first screen. Here is how I fixed each, starting with critical CSS from critters at postbuild.
- Published
The first screen of a static Next.js site is slow on PSI mobile for 3 reasons: render-blocking CSS, font files that load too early, and JS that must run before content shows. This site is Next.js 16 with output: 'export', and each of the 3 has its own trap that I already fell into. The critical CSS, font and first-screen fixes live in scripts/inline-critical-css.js and a few component conventions.
Critical CSS for Next.js: run critters at postbuild, skip experimental.optimizeCss
The script runs at postbuild, after next build has written out/:
"postbuild": "node scripts/inline-critical-css.js && node scripts/generate-sitemaps.js && node scripts/check-seo.js && node scripts/check-links.js"
For every out/**/*.html, critters inlines the CSS the first screen needs. The full CSS file loads without blocking render (media="print" plus onload, with a <noscript> fallback). The core config:
const critters = new Critters({
path: OUT,
publicPath: '/',
preload: 'media',
inlineFonts: false,
preloadFonts: false,
allowRules: ['html:not(.dark)'],
reduceInlineStyles: false,
})
I do not turn on Next's experimental.optimizeCss. Its critters pass runs on HTML that does not yet contain the content of the dynamic layouts (layouts/index.js), so it misses most of the first-screen CSS. My script reads the HTML after the export is finished.
3 details keep it correct:
pages/_document.jsrenders thedarkclass up front so critters keeps the dark rules. Light mode variables live underhtml:not(.dark), which does not match the static DOM, soallowRuleskeeps them by hand.- The font
url(../media/…)is relative to/_next/static/chunks/. Once inlined into HTML it must become an absolute path, otherwise the font returns 404 and text falls back to the fallback font. - Next's
<link rel="preload" … as="style">tags are removed, because the CSS already loads without blocking and that preload only competes with the LCP image for bandwidth.
out = out.replace(/<style>[\s\S]*?<\/style>/g, (style) => style.replace(/url\(\.\.\//g, 'url(/_next/static/'))
The script throws when the number of pages with a <style> differs from the number of HTML files (chỉ N/M trang có CSS inline). To check by eye, block **/*.css in Playwright and compare the first-screen screenshot against the full-CSS version.
Never inline @font-face with url(): PSI counts fonts finished before paint as render-blocking
A face inlined into HTML makes every first-screen font file load immediately, at VeryHigh priority. Any file that finishes before the first paint is counted by PSI's Lantern as render-blocking. The symptom I saw: mobile FCP jumping 0.8s ↔ 2s between runs. inlineFonts: false and preloadFonts: false above exist to avoid exactly this. The real fonts load with the full CSS file.
One thing has to be added back. With inlineFonts off, critters drops every @font-face, including the next/font fallback face (local(Arial) tuned with size-adjust to match the Inter and JetBrains Mono metrics). Without it, the first paint uses the browser default font and text jumps when the full CSS arrives. The script injects exactly that kind of face by hand:
function fallbackFaces(html) {
const faces = new Set()
for (const [, href] of html.matchAll(/href="(\/_next\/static\/[^"]+\.css)"/g)) {
const css = fs.readFileSync(path.join(OUT, href), 'utf8')
for (const face of css.match(/@font-face\{[^}]*src:local\([^}]*\}/g) || []) faces.add(face)
}
return [...faces].join('')
}
Drop the latin-ext face: Vietnamese pages skip 86 KB of extra font
next/font declares every Google Fonts subset, and subsets only decides what gets preloaded. The characters ơ ư ă đ sit in both the latin-ext and vietnamese ranges. The face declared later is checked first, so a Vietnamese page always downloads Inter latin-ext at 86 KB (and JetBrains Mono latin-ext) even though the vietnamese face already has the glyphs.
The site content uses no character that exists only in latin-ext, so the script removes that face from the CSS:
const LATIN_EXT_FACE = /@font-face\{[^}]*unicode-range:U\+100-2BA[^}]*\}/g
The regex depends on the unicode-range string Google emits. If Google changes the range, the regex misses silently and the extra font comes back, so the script counts the faces it dropped and warns when that is 0:
inline-critical-css: không thấy @font-face latin-ext nào để bỏ, kiểm lại LATIN_EXT_FACE
The cost: a page that uses a character found only in latin-ext (ł, ş, č…) gets that character in Arial.
The first screen must not wait for JS: Reveal, the LCP image and third-party scripts
Component conventions:
Revealand the fade onImageonly hide elements that sit below the screen at mount. Elements on the first screen are always visible and never wait for JS.- The LCP image gets
priority. Thecomponents/Image.jsxwrapper setsfetchPriority="high"itself, because Next 16 does not. - Project images in
public/screenshots/use.webpon the page, and a same-named.jpgstays forog:image(components/Seo.jsx). A new screenshot needs both generated. - The
-720.webpvariant forsrcsetis produced byscripts/resize-screenshots.jsatprebuild(it skips-mobile.webp).
A static export has no Image Optimization API, so next.config.js uses the custom loader lib/image-loader.js. Only /screenshots/*.webp get a srcset (the 720 variant for candidates under 1024px). Every other image is marked unoptimized by components/Image.jsx or MDXImage. If you call next/image directly somewhere new, pass unoptimized yourself, otherwise the image goes through the loader.
GA4 and AdSense must not block the first screen either. components/DeferredScripts.jsx loads gtag.js and adsbygoogle.js after the first interaction, or when idle 4s after load. Those 2 scripts are about 1.3 MB of uncompressed JS, so do not move them back to a <script> in <head>.
Measure on the live site, and what a local build cannot check
I keep PSI scores out of this post. Scores swing between runs, and this post has no measurement with a command behind it. The measuring procedure is in docs/operations.md: the psi command against the live site, 5 runs, report the median. Local Lighthouse cannot replace that number.
2 trade-offs remain. First, latin-ext characters fall back to Arial, which is fine while content is only Vietnamese and English. Second, everything above depends on the HTML after export: changing the out/ structure, upgrading critters or upgrading Next means opening the real pages again, because no test suite catches it for you.
Related posts
all posts →- Removing @tailwindcss/aspect-ratio: a silent failure that made every cover 0px tallThe aspect-ratio plugin replaces theme.aspectRatio, so Tailwind core stops emitting aspect-video. Image boxes collapse to 0px, every cover vanishes, and the build stays green.read more →
- SEO and link gates on the Next.js build output: check the built HTML, not the source2 postbuild gates read out/**/*.html: canonical, og:image, two-way hreflang, duplicate titles, sitemap xhtml:link and dead internal links. A failure stops the build before deploy.read more →
- Bilingual Next.js static blog: translationOf, hreflang and a build-failing gateEach post is 2 Markdown files joined by a single translationOf line. The URL map, hreflang tags, language switch and a build-failing gate all derive from that line, with no Next i18n.read more →
- Dropping the server: moving a static Next.js site to Cloudflare Workers Static AssetsThis site is only HTML, JS and images, yet it used to live on a 2 GB RAM VPS shared with about 28 other sites. How I moved it to Workers Static Assets: translating the nginx config into _redirects and _headers, why requests do not count against the Free plan limit, and 2 places I tripped after the move.read more →