@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.
Usage
First, we need to install @next/font
package:
npm install @next/font
Inside the 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.
Inside the <style>
tag we're defining two CSS variables --inter-font
and --firaCode-font
which we will later reference in the tailwind.config.js
file.
font-display
The font-display property determines how a font face is displayed based on whether and when it is downloaded and ready to use.
@next/font
uses font-display: optional
by default. Other available options are:
auto
The font display strategy is defined by the user agent.
block
Gives the font face a short block period and an infinite swap period.
swap
Gives the font face an extremely small block period and an infinite swap period.
fallback
Gives the font face an extremely small block period and a short swap period.
optional
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
if @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.