Utilizing the Next.js Font Optimization Feature
Illustrate how to enable and configure the built-in font optimization feature in Next.js 14 to automatically inline font CSS and improve font loading efficiency.
// next.config.js
module.exports = {
experimental: {
optimizeFonts: true,
},
};
In your Next.js project, create or edit the `next.config.js` file to include the experimental flag for `optimizeFonts`. Setting it to true enables the automatic font optimization.
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
{/* Preload fonts here if needed using <link> tags */}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument;
If additional font customization is needed, such as preloading fonts, you can modify the `_document.js` file in your pages directory. With the font optimization feature enabled, Next.js will automatically inline font CSS during the build process. Preloading fonts can still be done manually if needed for further performance improvements.