I’m working on a Next.js 14 project, where I’ve organized my Google Fonts imports in a fonts.ts file. I only import the fonts I need for specific pages, yet in production, all the fonts from the fonts.ts file are preloaded in the of every page, even if they are not used.
Here’s my fonts.ts:
import { Allan, Barlow_Condensed, Caesar_Dressing, Comfortaa, Dancing_Script, Edu_NSW_ACT_Foundation, Englebert, Grenze_Gotisch, Hind_Madurai, Inter, Love_Ya_Like_A_Sister, Oregano, Ranga, Roboto, Snippet, Stick_No_Bills, Sunshiney, Teko, Truculenta } from 'next/font/google';
export const barlowCondensed = Barlow_Condensed({ subsets: ['latin'], weight: '400', display: 'swap' });
export const teko = Teko({ subsets: ['latin'], weight: '400', display: 'swap' });
export const comfortaa = Comfortaa({ subsets: ['latin'], weight: ['400', '600'], display: 'swap' });
export const inter = Inter({ subsets: ['latin'], weight: ['400', '800'], display: 'swap' });
export const roboto = Roboto({ subsets: ['latin'], weight: ['400', '700'], display: 'swap' });
// Other fonts for customization
export const truculenta = Truculenta({ subsets: ['latin'], weight: '400', display: 'swap' });
//... additional font imports here
Example of a page (Home.tsx) where I only use specific fonts:
import LandingHeader from '@/components/landingPage/LandingHeader';
import '../sass/landing/LandingGlobal.scss';
import MenuHeroSection from '@/components/landingPage/MenuHeroSection';
import { inter } from '@/lib/fonts';
import MenuFeatureSection from '@/components/landingPage/MenuFeatures';
// ...other imports
export default function Home() {
return (
<main style={inter.style} className='landing-page'>
<LandingHeader />
<MenuHeroSection />
<MenuFeatureSection />
{/* Other sections */}
</main>
);
}
The Problem:
In development mode, everything works as expected; only the fonts I import are loaded. However, in production mode, all the fonts from fonts.ts are preloaded in the of the page, even if they are not used in that specific page.
For example, in the production build of my homepage, I see this in the head:
<link rel="preload" href="/_next/static/media/51b9f9f30f86448c-s.p.woff2" as="font" crossorigin="" type="font/woff2"/>
<link rel="preload" href="/_next/static/media/063bf2671c6c4452-s.p.woff2" as="font" crossorigin="" type="font/woff2"/>
<!-- And many more font preloads -->
This behavior results in unnecessary font preloading, affecting page performance.
My Question:
How can I ensure that only the fonts actually used on a specific page are preloaded in production?