There are several methods to import custom fonts into a Next.js project. Here, I will detail several common methods and provide examples.
Method 1: Using CSS or Sass
-
Place the font files: First, place the font files in the
fontsfolder under the public directory (typically thepublicfolder). For instance, you can placeRoboto-Regular.ttfin thepublic/fontsdirectory. -
Create a CSS file: Create a CSS file in the
stylesdirectory, such asfonts.css. -
Import the font: Use the
@font-facerule in thefonts.cssfile to import the font. For example:
css@font-face { font-family: 'Roboto'; src: url('/fonts/Roboto-Regular.ttf') format('truetype'); font-weight: normal; font-style: normal; }
- Import the CSS file in
_app.jsor_app.tsx:
jsximport '../styles/fonts.css';
- Use the font: In any component within the project, you can now use the
Robotofont via CSS:
cssbody { font-family: 'Roboto', sans-serif; }
Method 2: Using next/head
If you simply want to quickly reference an online font (such as Google Fonts), you can use next/head to add the font link in the head of a specific page or in _app.js.
jsximport Head from 'next/head'; function MyApp({ Component, pageProps }) { return ( <> <Head> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet" /> </Head> <Component {...pageProps} /> </> ); } export default MyApp;
Use the font directly in CSS, as shown in the CSS example above.
Method 3: Using font loaders (such as fontsource)
If you use npm or yarn, you can choose to use packages like fontsource to manage fonts. This method allows you to manage font dependencies via npm instead of manually downloading font files.
- Install the fontsource package:
bashnpm install @fontsource/roboto
Or
bashyarn add @fontsource/roboto
- Import the font in
_app.jsor_app.tsx:
jsximport '@fontsource/roboto/400.css'; import '@fontsource/roboto/700.css';
- Use the font: Directly use the
Robotofont in CSS.
These are several common methods to import custom fonts into a Next.js project. Each method has its use cases, and you can choose the appropriate one based on your project requirements and personal preferences.