Fontsource Logo

Documentation

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

⬤⬤

npm install @fontsource-variable/open-sans

sh

2. Import CSS

Modify app/layout.tsx to include the following code:

⬤⬤

import "@fontsource-variable/open-sans/wght.css";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}

tsx

Note: You can also import fonts in individual layout.tsx or page.tsx files to scope them to specific routes.

3. Usage

You can now use the imported fonts in your Next.js project.

⬤⬤

h1 {
font-family: "Open Sans Variable", sans-serif;
}

css

Pages Router

With the Pages Router, you can import fonts in your custom _app.tsx file.

1. Installation

⬤⬤

npm install @fontsource-variable/open-sans

sh

2. Import CSS

Modify _app.tsx to include the following code:

⬤⬤

import "@fontsource-variable/open-sans/wght.css";
function MyApp({ Component, pageProps }: { Component: any; pageProps: any }) {
return <Component {...pageProps} />;
}
export default MyApp;

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.

⬤⬤

h1 {
font-family: "Open Sans Variable", sans-serif;
}

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.