Integrating Google Fonts with Next.js Optimally
Show the steps to correctly integrate Google Fonts using the `next/google-fonts` package to efficiently load fonts in a Next.js app while minimizing impact on performance.
// Step 1: Install the next-google-fonts package
// Run the following command in your terminal
npm install @next/font-google
Installs the @next/font-google package to be used for font optimization.
// Step 2: Create a _document.js file in your pages directory if it doesn't already exist
// Add the following imports and class to your _document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { GoogleFont } from '@next/font-google';
export default class MyDocument extends Document {
render() {
return (
<Html>
<Head>
{GoogleFont({ href: 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap' })}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
Defines a custom Document and includes the Google font by using the GoogleFont component from the next/font-google package. The href attribute should point to the Google Fonts CSS URL of your chosen font(s).
// Step 3: Use the font in your application
// In your CSS (e.g., styles/global.css)
body {
font-family: 'Roboto', sans-serif;
}
// Or a CSS-in-JS solution (e.g., styled-jsx or emotion)
<style jsx>{`
body {
font-family: 'Roboto', sans-serif;
}
`}</style>
This step ensures the font is applied within your application by setting the 'font-family' in your stylesheet to the Google Font you included in the _document.js file.