Search code examples
javascriptnext.jsfonts

Error while trying to add external local fonts in nextJS


I'm trying to add local font to my NextJS + TailwindCSS project. I have added the font inside public/fonts folder and I'm following the docs:

This is my code

import localFont from '@next/font/local'
const inter = Inter({
    subsets: ['latin'],
})

const recoleta = localFont({
    src: 'fonts/Recoleta-Regular.ttf',
    fontFamily: 'Recoleta',
})

And I'm getting this error from the terminal.

I need help on which folder to add it or how to configure it perfectly.

Module not found: Can't resolve './fonts/Recoleta-Regular.ttf'



Solution

  • Had this error and fixed the issue by setting it up as such. Used https://nextjs.org/docs/api-reference/next/font#src for assistance. Using app folder.

    page.tsx:

    import CustomFont from '@next/font/local'
    
    const cfont = CustomFont({
      src: '../public/fonts/cfont.ttf',
      variable: '--font-cfont',
    })
    
    export default function Home() {
      return (
        <div className={`${cfont.variable}`}>
          <div className="font-cfont">
            Test
          </div>
        </div>
      )
    }
    
    
    

    tailwind.config.js:

    
    const { fontFamily } = require('tailwindcss/defaultTheme')
    
    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./app/**/*.{js,ts,jsx,tsx}",
        "./pages/**/*.{js,ts,jsx,tsx}",
        "./components/**/*.{js,ts,jsx,tsx}",
      ],
      theme: {
        extend: {
          fontFamily: {
            cfont: ['var(--font-cfont)', ...fontFamily.sans],
          },
        },
      },
      plugins: [],
    }