Next.js
Next.js is a React framework for building web applications. Importing fonts depends on the router you are using. Below are the steps to import fonts into a Next.js project.
App Router
To import fonts into a Next.js project using the App Router, you can simply import the CSS file directly into your root layout file.
1. Installation
⬤⬤
sh
2. Import CSS
Modify app/layout.tsx to include the following code:
⬤⬤
tsx
Note: You can also import fonts in individual
layout.tsxorpage.tsxfiles to scope them to specific routes.
3. Usage
You can now use the imported fonts in your Next.js project.
⬤⬤
css
Pages Router
With the Pages Router, you can import fonts in your custom _app.tsx file.
1. Installation
⬤⬤
sh
2. Import CSS
Modify _app.tsx to include the following code:
⬤⬤
tsx
Note: You can also import fonts in individual page components, but the CSS will only be present within that page and not globally.
3. Usage
You can now use the imported fonts in your Next.js project.
⬤⬤
css
Comparison to next/font
Next.js offers a built-in way to load fonts using the next/font package. This package serves as a straightforward alternative to Fontsource with a simple setup. It embeds the CSS from the Google Fonts API, eliminating an additional round-trip response. It performs well for most use cases and is a good choice if you do not need to customise the font loading behaviour.
We recommend using Fontsource if you need more control over versioning your dependencies and do not want an invisible abstraction over the Google Fonts API. We also offer an escape hatch to directly modify the @font-face rules suitable for more advanced use cases.