For external fonts, you can simply add the preload link in your head component;
<link rel="preload" href="https://fonts.googleapis.com/css?family=Play&display=swap" as="font" />
As for the internal fonts that you have in your public
folder, this requires;
file-loader
configuration in next.config.js
, this is to resolve the hashed filename
- Type definition for the fonts
- Then import it into your head
Which you can find my sample below;
I created a Layout.tsx
which wraps my other components, which its main purpose is that there would not be duplicated meta tags - But this is unrelated to the question.
Here's the code I have in Next@10.0.5
- to preload both external and internal fonts.
App.tsx
function App({ Component, pageProps }: AppProps): JSX.Element {
const queryClient = new QueryClient();
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Provider store={store}>
<main className="main-container position-relative" data-testid="main-container">
<HeaderComp />
<Layout>
<Component {...pageProps} />
</Layout>
<FooterComp />
<ScrollToTop />
</main>
</Provider>
</Hydrate>
</QueryClientProvider>
);
}
Layout.tsx
import fontGilroyBold from "@assets/fonts/gilroy/Gilroy-Bold.woff";
const Layout: React.FunctionComponent = ({ children }) => {
return (
<div className="content font-play position-relative">
<Head> {* next/head *}
{/* ...metaTags */}
<link rel="preload" href={fontGilroyBold} as="font" />
<link rel="preload" href="https://fonts.googleapis.com/css?family=Play&display=swap" as="font" />
</Head>
{children}
</div>
);
};
next-env.d.ts
...
declare module "*.woff";
declare module "*.woff2";
...
next.config.js
const nextConfig = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
/**
* Override some of the existing loaders
*/
// ...
/**
* Font imports in the code repository will be resolved as relative path
*/
config.module.rules.push({
test: /gilroy\/.+\.(woff|woff2)$/,
use: {
loader: "file-loader",
options: {
/** Stolen configuration from pre-existing "config.module.rules[2]" */
outputPath: "static/fonts/gilroy/",
publicPath: "/_next/static/fonts/gilroy/",
limit: 1,
},
},
});
return config;
},
};