
Font Component in NextJS
🔤 Font Component in Next.js
Next.js provides built-in support for custom fonts using the next/font
package. This allows you to optimize and load fonts efficiently, improving performance and avoiding layout shifts.
📌 1. Installing Google Fonts in Next.js
The easiest way to add Google Fonts is by using the next/font/google
package.
🔹 Install next/font
(If not installed)
npm install next@latest
🔹 Using a Google Font (e.g., Inter)
<h1 className={myFont.className}>Custom Font!</h1>;}
✅ No external requests
✅ Works offline
📌 3. Using Fonts in Global CSS
Instead of components, you can load fonts in global CSS.
🔹 Add Google Fonts in _app.js
import "@/styles/globals.css";
🔹 Modify globals.css
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');body { font-family: 'Roboto', sans-serif;}
✅ Good for global font styles
📌 4. Best Practices
✔️ Use next/font/google
for performance optimization
✔️ Use next/font/local
for self-hosted fonts
✔️ Avoid @import
in CSS for better speed