Self-hosted fonts doesnt works on Next.js

2.6k views Asked by At

What I want and what I wonder

I would like to use self-hosted font within a Next.js application

What i already tried

https://i.stack.imgur.com/AuIwB.png

https://i.stack.imgur.com/P6ekH.png

The result

In both cases CSS only recognizes the last font

Important

My Bold, Medium, Italic and regular fonts are separeted file, they are all in woff2 format. I already tried to use diferente @font-face for each file (bold,regular and medium) and name each one, it works, but i think could be a more eficient way

1

There are 1 answers

0
herrstrietzel On BEST ANSWER

You need to add one @font-face per style (including weights and italic versions).
The font-family name should stay the same!
Otherwise styles won't get mapped correctly to the specific font files.

Currently you're just overriding your first url – "Metropolis-Medium.woff2" won't be loaded at all since it's replaced by "Metropolis-Bold.woff2".

Multiple URLs can be used for fallback formats (e.g woff2, woff2, ttf etc.)

Without any font-weight values the browser will map the family-name "Metropolis" to "Metropolis-Bold.woff2" file and regular font-weight (or 400).

For better compatibility, you should use more verbose rules like so:
(Albeit some browsers might be more forgiving)

@font-face {
  font-family: Metropolis;
  font-weight: 400;
  font-style: normal;
  src: url("../../../public/fonts/metropolis/Metropolis-Regular.woff2")
      format("woff2"),
    url("../../../public/fonts/metropolis/Metropolis-Regular.woff")
      format("woff");
}

@font-face {
  font-family: Metropolis;
  font-weight: 400;
  font-style: italic;
  src: url("../../../public/fonts/metropolis/Metropolis-Italic.woff2")
      format("woff2"),
    url("../../../public/fonts/metropolis/Metropolis-Italic.woff")
      format("woff");
}

@font-face {
  font-family: Metropolis;
  font-weight: 500;
  font-style: normal;
  src: url("../../../public/fonts/metropolis/Metropolis-Medium.woff2")
      format("woff2"),
    url("../../../public/fonts/metropolis/Metropolis-Medium.woff")
      format("woff");
}

@font-face {
  font-family: Metropolis;
  font-weight: 700;
  font-style: normal;
  src: url("../../../public/fonts/metropolis/Metropolis-Bold.woff2")
      format("woff2"),
    url("../../../public/fonts/metropolis/Metropolis-Bold.woff") format("woff");
}

body {
  font-family: Metropols, sans-serif;
}

.medium {
  font-weight: 500;
}

.bold {
  font-weight: 700;
}