OiO.lk Blog CSS Next.js failing to apply font to text
CSS

Next.js failing to apply font to text


I am starting a new project with NextJS (version 14.2.13). I created the project using create-next-app, then I have imported two fonts from google fonts using the following code:

./app/fonts.ts

import { Montserrat, Open_Sans } from 'next/font/google'

export const montserrat = Montserrat({
    subsets: ['latin'],
    variable: '--font-montserrat',
    display: 'swap',
});

export const open_sans = Open_Sans({
    subsets: ['latin'],
    variable: '--font-open-sans',
    display: 'swap',
});

Following the official documentation I imported the fonts and added them to the <body> tag in my root layout:

.app/layout.tsx

import {montserrat, open_sans} from './fonts'
import "./globals.css";

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={`${montserrat.variable} ${open_sans.variable} antialiased`}>
          {children}
      </body>
    </html>
  );
}

However, something does not work.

  1. When applying the font to an element, the font does not get applied:

.app/page.tsx

import {montserrat} from "./fonts";


export default function Home() {
  return (
      <>
          <h1 className={`${montserrat.className}`}>Hello World</h1>
      </>
  );
}
  1. When defining in the global stylesheet, the variables do not exist. this throws an eslint warning in the IDE and the browser devtools return that the variable is not defined upon inspection.

.app/globals.css

h1 {
  font-family: var(--font-open-sans);
}

h6 {
  font-family: var(--font-montserrat);
}

Why are my fonts not getting applied? I will add that I have been through the official documentation, but it is lacking at best even when followed to the letter.

Any help will be much appreciated.

Edit:
I am adding my config files, just in case they provide any insight

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./app",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./app/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

tailwind.config.ts
import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      colors: {
        background: "var(--background)",
        foreground: "var(--foreground)",
      },
    },
  },
  plugins: [],
};
export default config;



You need to sign in to view this answers

Exit mobile version