Font Optimization in Next.js – Self-Hosting Google and Local Fonts with next/font

The next/font module in Next.js enables automatic font optimization by self-hosting Google and local fonts. This eliminates external requests, improves privacy, and prevents layout shift. This article explains how to use next/font with Google fonts, local font files, and multiple font variants for better performance and design flexibility.

Google FontsLocal Fontsnext/fontSelf-hosted fonts

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۳ آبان ۱۴۰۴

Introducing next/font


The next/font module automatically optimizes fonts and removes external network requests. Fonts are self-hosted and served as static assets, improving performance and preventing layout shift.


How to Use


Import a font from next/font/google or next/font/local, call it as a function, and apply the generated className to your layout or component:


// app/layout.tsx
import { Geist } from 'next/font/google'

const geist = Geist({ subsets: ['latin'] })

export default function Layout({ children }) {
  return (
    <html lang="en" className={geist.className}>
      <body>{children}</body>
    </html>
  )
}

Using Google Fonts


Google Fonts can be self-hosted using next/font/google. Fonts are stored as static assets and served from your own domain, with no requests sent to Google.


Variable fonts are recommended for better performance. If not available, specify a weight:


// app/layout.tsx
import { Roboto } from 'next/font/google'

const roboto = Roboto({ weight: '400', subsets: ['latin'] })

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={roboto.className}>
      <body>{children}</body>
    </html>
  )
}

Using Local Fonts


To use a local font, import it from next/font/local and specify the path to the font file. Fonts can be stored in the public folder or colocated inside the app directory:


// app/layout.tsx
import localFont from 'next/font/local'

const myFont = localFont({ src: './my-font.woff2' })

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={myFont.className}>
      <body>{children}</body>
    </html>
  )
}

Using Multiple Files for a Font Family


You can define multiple font files with different weights and styles:


const roboto = localFont({
  src: [
    { path: './Roboto-Regular.woff2', weight: '400', style: 'normal' },
    { path: './Roboto-Italic.woff2', weight: '400', style: 'italic' },
    { path: './Roboto-Bold.woff2', weight: '700', style: 'normal' },
    { path: './Roboto-BoldItalic.woff2', weight: '700', style: 'italic' },
  ],
})

Conclusion


The next/font module in Next.js offers a simple and powerful way to optimize fonts. Whether using Google Fonts or local assets, you can improve performance, reduce layout shift, and deliver a fast, beautiful experience across your application.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه