nextjs-font-optimization-next-font-google-local-tailwind

Fonts are the outfit of your page — and next/font makes them fast, secure, and beautiful. With automatic optimization, zero external requests, and no layout shift, next/font lets you load Google or local fonts with ease. This article shows how to use next/font with Tailwind CSS, organize font definitions, preload fonts, and follow best practices.

next/fontGoogle FontsTailwind CSS

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

Why Use next/font?


Old Problemnext/font Solution
Google requestDownloaded at build time
Layout ShiftCLS = 0
Privacy leakNo trackers
Slow loadingLocal fonts

1. Google Fonts — As Easy as Breathing


import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
})

const roboto_mono = Roboto_Mono({
  subsets: ['latin'],
  weight: '400',
  variable: '--font-mono',
})

In layout:

<html className={`${inter.variable} ${roboto_mono.variable}`}>

2. Local Fonts — Your Custom Love


import localFont from 'next/font/local'

const vazir = localFont({
  src: './fonts/Vazir.woff2',
  variable: '--font-vazir',
  display: 'swap',
})

For multiple weights:

src: [
  { path: './Vazir-Thin.woff2', weight: '100' },
  { path: './Vazir-Regular.woff2', weight: '400' },
  { path: './Vazir-Bold.woff2', weight: '700' },
]

3. Tailwind CSS + next/font = True Love


// layout.tsx
<html className={`${inter.variable} ${roboto.variable} antialiased`}>

// tailwind.config.ts
fontFamily: {
  sans: ['var(--font-inter)'],
  mono: ['var(--font-mono)'],
}

In JSX:

<p className="font-sans">Regular text</p>
<code className="font-mono">Code</code>

4. Font Definitions File — Clean & Organized


// styles/fonts.ts
export const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
export const vazir = localFont({ src: './Vazir.woff2', variable: '--font-vazir' })

// app/page.tsx
import { inter, vazir } from '@/styles/fonts'

<h1 className={vazir.className}>Hello World</h1>
<p className={inter.className}>Welcome</p>

5. How to Apply Fonts


  • className: <p className={inter.className}>
  • style: <p style={inter.style}>
  • CSS Variable: font-family: var(--font-inter)

6. Preloading — Only What’s Needed


WhereWhat Gets Preloaded
app/layout.tsxAll pages
app/dashboard/layout.tsxOnly dashboard
app/page.tsxOnly home

7. Best Practices


  • ✅ Use variable for Tailwind
  • ✅ Define subsets to reduce size
  • ✅ Use display: 'swap' to avoid CLS
  • ✅ Define fonts in fonts.ts for clarity
  • ✅ Use variable fonts when possible

8. Real-World Example: E-Commerce Site


// styles/fonts.ts
export const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
export const playfair = Playfair_Display({ weight: '700', variable: '--font-title' })

// layout.tsx
<html className={`${inter.variable} ${playfair.variable}`}>
  <body className={inter.className}>{children}</body>
</html>

// page.tsx
<h1 className={`${playfair.className} text-4xl`}>My Store</h1>
<p className="text-lg">Best products, best prices</p>

9. Final Checklist


  • ✅ Used next/font
  • ✅ Defined subsets
  • ✅ Used variable for Tailwind
  • ✅ Fonts in fonts.ts
  • ✅ Used display: 'swap'
  • ✅ CLS = 0

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

مقالات مرتبط

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.

ادامه