Self-Hosting Fonts to Avoid External Requests
Offer a guide for self-hosting font files in a Next.js application, eliminating reliance on external font services and improving load times through better control over caching.
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html>
<Head>
<link
rel='preload'
href='/fonts/custom-font.woff2'
as='font'
type='font/woff2'
crossOrigin='anonymous'
/>
{/* Add more font preload links if necessary */}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
This Next.js _document.js file preloads custom fonts from the local public directory, optimizing load times and reducing external requests.
@font-face {
font-family: 'CustomFont';
font-style: normal;
font-weight: 400;
font-display: swap;
src: local('CustomFont'), url('/fonts/custom-font.woff2') format('woff2');
}
body {
font-family: 'CustomFont', sans-serif;
}
This is a CSS snippet to be included in your global stylesheet. It defines a @font-face rule to use a locally hosted font and specifies the path to the font file in the `src` attribute.
import { Global, css } from '@emotion/react';
const GlobalStyles = () => (
<Global
styles={css`
@font-face {
font-family: 'CustomFont';
font-style: normal;
font-weight: 400;
font-display: swap;
src: local('CustomFont'), url('/fonts/custom-font.woff2') format('woff2');
}
body {
font-family: 'CustomFont', sans-serif;
}
`}
/>
);
export default GlobalStyles;
This JavaScript snippet demonstrates how to use Emotion (a popular CSS-in-JS library) in a Next.js app to inject a global style that includes the @font-face rule, defining the locally hosted custom font.