0
0
NextJSframework~30 mins

Font optimization and self-hosting in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Font Optimization and Self-Hosting in Next.js
📖 Scenario: You are building a Next.js website for a local bakery. You want the website to load fast and look great with a custom font. To do this, you will optimize font loading by self-hosting a Google font instead of loading it from an external server.
🎯 Goal: Build a Next.js app that uses a self-hosted Google font with font optimization enabled. You will add the font files, configure Next.js to load them efficiently, and apply the font to your page.
📋 What You'll Learn
Create a Next.js app with a basic page
Download and add the 'Roboto' font files to the project
Configure Next.js to self-host and optimize the 'Roboto' font
Apply the 'Roboto' font to the main page content
💡 Why This Matters
🌍 Real World
Many websites want to load fonts quickly and reliably without depending on external servers. Self-hosting fonts with Next.js font optimization improves load speed and user experience.
💼 Career
Web developers often optimize font loading to improve site performance and accessibility. Knowing how to self-host and configure fonts in Next.js is a valuable skill for frontend roles.
Progress0 / 4 steps
1
Set up the Next.js page
Create a file called app/page.tsx with a default export of a React functional component that returns a <main> element containing the text Welcome to the Bakery.
NextJS
Need a hint?

This is the basic page component in Next.js 14 App Router. Use a function named Page that returns JSX.

2
Add Roboto font files to the project
Create a folder called public/fonts/roboto and add the font files Roboto-Regular.woff2 and Roboto-Bold.woff2 inside it. Then, create a file app/fonts.ts and export a constant called roboto using Next.js localFont function to load these two font weights from /fonts/roboto/Roboto-Regular.woff2 and /fonts/roboto/Roboto-Bold.woff2.
NextJS
Need a hint?

Use localFont from next/font/local to load font files from the public folder. Specify weights 400 and 700.

3
Apply the Roboto font to the page
Import the roboto font from ./fonts in app/page.tsx. Then, add the font's className to the <main> element so the text uses the Roboto font.
NextJS
Need a hint?

Use the className property from the font object to apply the font style.

4
Enable font optimization in next.config.js
Create or update next.config.js at the project root to export a config object with experimental.fontLoaders set to use the local font loader. This enables Next.js font optimization for self-hosted fonts.
NextJS
Need a hint?

This config tells Next.js to optimize local fonts. Add it to next.config.js at the root.