@next/font tips & tricks
The @next/font package introduced in Next.js 13 allows for optimized self-hosting of any font file, enabling you to serve your own or fonts from Google Fonts and use them with CSS variables without causing a layout shift.
First, we need to install
npm install @next/font
next.config.js file we can globally define which font subsets to preload.
By doing this, we can reduce the size of the font file and significantly improve performance.
Integration with Tailwind CSS
An example from official docs:
However, I have found that this approach does not work for multiple fonts, so I am sharing an alternative workaround with you as well:
We're importing functions that represent selected Google font. Once imported, we can call those fucntions and pass them an optional configuration object.
In this example, we're passing
display: block which affects
font-display css property.
<style> tag we're defining two CSS variables
--firaCode-font which we will later reference in the
The font-display property determines how a font face is displayed based on whether and when it is downloaded and ready to use.
font-display: optional by default. Other available options are:
The font display strategy is defined by the user agent.
Gives the font face a short block period and an infinite swap period.
Gives the font face an extremely small block period and an infinite swap period.
Gives the font face an extremely small block period and a short swap period.
Gives the font face an extremely small block period and no swap period.
In case we opt for the default behavior, that may result in the display of an auto-generated fallback font
@next/font does not load within 100ms. To ensure that our intended font is always displayed, we can pass
display: block or
display: swap as an option.