With Next 13 came @next/fonts
which handled loading of fonts on NextJS. In this post,
I go through on how to load google fonts from @next/fonts
on your MaterialUI or JoyUI
project.
npm i @next/font
Customization should always happen where design tokens will be generated from. In case of JoyUI the best place is the theme configuration file.
We will be importing the font name which we will be using.
import { Montserrat } from '@next/font/google'; // note the /google subdirectory
This font name has quite a class name convention, but no, we are not calling with the new
keyword.
A regular call should suffice.
const montserrat = Montserrat({ subsets: ['latin'] });
The function accepts an options object to configure the font based on our needs. The most common options you will be using are:
subsets: Array<string>
weight: Array<string>
If you go to google fonts, you will notice a variable keyword on some fonts. These fonts do not require the weight to be specified. You can freely use their weight without explicitly importing them.
For non-variable fonts, you do have to specify which font weights you will be using.
const hindSiliguri = Hind_Siliguri({ weight: ['400'], subsets: ['latin'] });
And yes, it's an array of strings, not array of numbers.
Finally, the last part is to use the object returned and extracting the property <object>.style.fontFamily
to use wherever you'd like that font.
const themeConfig = {
fontFamily: {
body: `${montserrat.style.fontFamily}, sans-serif`,
display: `${montserrat.style.fontFamily}, sans-serif`,
},
};