# Next.js [#nextjs]

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 [#app-router]

To import fonts into a Next.js project using the [App Router](https://nextjs.org/docs/app), you can simply import the CSS file directly into your root layout file.

### 1. Installation [#1-installation]

```sh
npm install @fontsource-variable/open-sans
yarn add @fontsource-variable/open-sans
pnpm add @fontsource-variable/open-sans
bun add @fontsource-variable/open-sans
```

### 2. Import CSS [#2-import-css]

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

```tsx
import "@fontsource-variable/open-sans/wght.css";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
```

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

### 3. Usage [#3-usage]

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

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

## Pages Router [#pages-router]

With the [Pages Router](https://nextjs.org/docs/pages/building-your-application/routing/custom-app), you can import fonts in your custom `_app.tsx` file.

### 1. Installation [#1-installation-1]

```sh
npm install @fontsource-variable/open-sans
yarn add @fontsource-variable/open-sans
pnpm add @fontsource-variable/open-sans
bun add @fontsource-variable/open-sans
```

### 2. Import CSS [#2-import-css-1]

Modify `_app.tsx` to include the following code:

```tsx
import "@fontsource-variable/open-sans/wght.css";

function MyApp({ Component, pageProps }: { Component: any; pageProps: any }) {
  return <Component {...pageProps} />;
}

export default MyApp;
```

> **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 [#3-usage-1]

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

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

## Comparison to `next/font` [#comparison-to-nextfont]

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.
