nextjs
  1. nextjs-optimizing-fonts

Next.js Optimizing Fonts

Next.js is a popular framework for building server-rendered React applications. It comes with various optimizations to improve performance, and one of the optimizations is optimizing fonts. In this guide, we will learn how to optimize fonts in Next.js.

Example

// next.config.js

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.module.rules.push({
      test: /\.(woff|woff2|eot|ttf|otf)$/i,
      type: 'asset/resource',
      generator: {
        filename: 'static/fonts/[hash][ext][query]'
      }
    })
    
    return config
  }
}

Explanation

Next.js uses webpack under the hood to build and bundle the application. If we want to optimize font loading, we can use webpack's asset modules to handle fonts.

In the above example, we use the asset/resource type to handle font files. This loads the font files as separate assets and copies them to the specified output directory. We also specify a custom filename that includes a hash to ensure that the font files get a unique name when we make changes to them.

Additionally, we can configure the font-display property in our CSS to control how the font is displayed while it's loading. By default, the value is auto, which means that the browser determines the best way to display the font.

Use

Optimizing fonts can improve site speed and performance. By using webpack's asset modules, we can load fonts asynchronously and control how they are displayed while they're loading.

Important Points

  • Use webpack's asset modules to handle font files.
  • Specify a custom filename for the font files to ensure unique names when we modify them.
  • Use the font-display property in CSS to control how the font is displayed while it's loading.

Summary

Optimizing fonts in Next.js can greatly improve site performance by loading fonts asynchronously and controlling how they're displayed while they're loading. By using webpack's asset modules and specifying a custom filename, we can ensure that the font files get unique names when we modify them. Additionally, we can configure the font-display property in our CSS to control how the font is displayed while it's loading.

Published on: