Blog>
Snippets

CSS Font Stack Best Practices in Next.js

Create an example of a well-designed CSS font stack that ensures maximum compatibility and performance across different browsers and platforms in a Next.js application.
import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp;
This is the typical _app.js file in a Next.js application where you import your global stylesheet. This is where you would ensure that your CSS font stack is included globally across your application.
body {
  font-family: 'Helvetica Neue', Arial, sans-serif;
}
Creating a global CSS file (typically named globals.css). In this CSS, we're setting up a font stack that starts with 'Helvetica Neue', followed by Arial and then falls back to the default sans-serif font on the system. This stack improves compatibility and performance across different browsers and platforms.
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/my-custom-font.woff2" as="font" type="font/woff2" crossOrigin="anonymous"/>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
In a custom Document (pages/_document.js), preloading custom fonts is utilized. Preloading fonts can boost performance as fonts are prioritized in the loading process. This example shows preloading a WOFF2 font which is widely supported and offers good compression.
@font-face {
  font-family: 'MyCustomFont';
  src: url('/fonts/my-custom-font.woff2') format('woff2');
}
Defining a custom font face in the CSS. This CSS rule specifies how to load a custom font named 'MyCustomFont' using the WOFF2 format, which should be included in the public/fonts/ directory of a Next.js application.