Tuesday, 24 January, 2023 UTC


Summary

One crucial aspect of any web application is the size and performance of its codebase. Next.js is a popular JavaScript framework for building server-rendered and statically-exported React applications.
Next.js provides the ability to automatically optimize an application’s code and minimize its bundle size. This can reduce the amount of data that needs to be transferred to the client, thereby improving performance. However, regularly analyzing your Next.js app’s bundle can help ensure that it is as optimized as possible and can also help identify potential areas for improvement.
In this article, we’ll discuss what a Next.js app bundle is and how bundle analyzer tools work. We’ll also demonstrate how to use the @next/bundle analyzer package to inspect your Next.js app bundles and improve their performance by ensuring they are as small and efficient as possible.
Jump ahead:
  • What is a Next.js app bundle?
  • What is the @next/bundle-analyzer?
  • Installing the @next/bundle-analyzer package
  • Configuring the Next.js app
  • Analyzing the Next.js app bundles
  • Inspecting the Next.js app bundles
    • Via the terminal
    • Via the browser
    • Using the sidebar filter
  • Creating an analysis command/script
What is a Next.js app bundle?
When you build a Next.js app, the code gets organized into small units called modules. These modules are bundled together by webpack, a popular JavaScript module bundler, to form a single file called a bundle. This bundle is then served to the client’s browser, which is executed to render the application.
As web applications become more complex and feature-rich, the size of their codebase can grow significantly. This can lead to slower loading times, which can frustrate users and negatively impact your app’s performance.
Additionally, larger codebases are often more challenging to maintain, making it harder to identify and fix bugs. By analyzing your app bundles, you can identify areas where you can optimize your code to reduce its size and improve its performance.
Several bundlers exist, but this article will focus on using one of the most popular bundling tools, the webpack-based @next/bundle-analyzer package.
What is @next/bundle-analyzer?
The @next/bundle-analyzer package is a plugin for the Next.js framework that allows you to analyze the size and composition of your app’s bundle. By identifying large or unnecessary code blocks, you can reduce overall bundle size, which can help optimize the performance of your Next.js app.
The bundle-analyzer plugin generates a visual report that provides information about the size and contents of your app bundle, making it easier to identify areas for optimization. @next/bundle-analyzer generates a static HTML file that contains a detailed report on your app’s codebase, including information on the size of each component and its dependencies.
Installing the @next/bundle-analyzer package
To use the @next/bundle-analyzer package, you must install it into an existing Next.js project. For this tutorial, I’ll use my open source project, Tech Career Roadmap, as the Next.js example project.
To start, install the package with either npm or Yarn:
# npm
npm install --save-dev @next/bundle-analyzer cross-env
# Yarn
yarn add -D @next/bundle-analyzer cross-env
You’ll notice that I also installed cross-env; we’ll use this package later in this article to set an environment variable. The cross-env package will allow us to set environment variables when running scripts in our package.json file without any errors, regardless of our platform-specific syntax or our OS.
Configuring the Next.js app
After you’ve installed the packages, you can enable the bundle analyzer by adding the following code to your next.config.js file:
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer({
  // your Next.js configuration
})
Analyzing the Next.js app bundles
To run an analysis for your app bundles, you’ll need to start your Next.js app in development mode with the ANALYZE environment variable set to true. Then, run the following command to view the analysis:
ANALYZE=true npm run build
This command will automatically:
  1. Create an analyze folder in your .next folder inside your root directory and create three files: client.html, nodejs.html, and edge.html
  2. Open the three files in your browser; the client.html file represents the client side, and the nodejs.html file represents the server side. At this time of writing, there is no data supplied for the Edge.html page. It will presumably represent edge APIs, but we have been unable to get confirmation from the package’s maintainers
  3. Provide bundle analysis information in your terminal
After the bundle analyzer has run, you can start inspecting your bundles:
Inspecting the Next.js app bundles
The @next/bundle-analyzer package provides a few ways to inspect your bundles: via the terminal, via the browser, and by using the sidebar filter. Let’s take a look.

Via the terminal

In the above image showing the terminal output, there’s a table displaying Page, Size, and First Load JS. Under the Page header is a list of all the pages in your Next.js app and chunks from the First Load JS bundle.
The First Load JS bundle is all the code shared or used by the app pages at initial load. Under the Size header, the package displays the file size of each page, bundle, and the chunks that make up the bundle.
Under the First Load JS, you can see the final size of the page or after the First Load JS has been added. The First Load JS size is also the initial size of the pages on initial load.
Next.js also color codes these sizes. Green tells us that the size is small and ok, while red indicates that the size is too large. If your First Load JS bundle size is shown in red, try to reduce it until it is displayed in green because the size of the bundle also affects the size and state of all your pages.

Via the browser

To inspect your app bundles in your browser, simply go to your browser to see two pages opened for you by the analyzer.
The first page, client.html, displays all the bundles for the client side:
The second page, nodejs.html, displays all the bundles for the server side:
If your app’s pages are not automatically loaded, or if you have already closed the browser, just go into the analyze folder and right-click on any file names in order to open them in your browser.
Next, simply hover over any of the bundles to see its stats. You’ll be able to see the Stat size, Parsed size, and Gzipped size of each bundle, as well as the bundles’ file path.
Here’s a little more detail on the size types:
  • Stat size: The size of the JavaScript bundle when served to the client; this is the size of the JavaScript code that the client’s web browser has to download and execute to run the app
  • Parsed size: The size of the bundle after the web browser has parsed it; this is the amount of memory that the JavaScript code takes up in the web browser after it has executed the code
  • Gzipped size: The size of the JavaScript bundle when compressed using the Gzip algorithm; this is the amount of data the client’s web browser must download to run the app. Gzip is a common compression algorithm used to reduce the size of web assets like JavaScript files. It can significantly reduce the amount of data transferred over the network
With the analyzer pages in the browser, you’ll be able to see which bundles are taking up the most space based on their size type. Also, the bundles are arranged based on their file sizes:
You can also right-click on the root bundle to view options related to that chunk. You can click Hide chunks to hide that particular chunk from view and view the rest, click Hide all other chunks to hide all other chunks except the one you clicked on, or click Show all chunks to show all the chunks that are currently hidden:

Using the sidebar filter

Another way to interact with and inspect your bundles is to use the sidebar filter. In the sidebar, you can specify a particular bundle or set of bundles that you’d like to view.
This approach can be useful for visualizing and inspecting smaller bundles quickly. You can also opt to have them ordered based on the size type: Stat, Parsed, or Gzipped:
You can search for modules using a particular file, folder, or phrase from your app; the analyzer will display results based on your search input:
Or, you can select an entry point for initial chunks (i.e., any of your app’s pages):
Creating an analysis command/script
To save time, you can also create a quick command/script to run in your package.json file. By doing so, you can avoid setting the environment variable on every call.
In your package.json file, add the following script:
"scripts": {
    …
    "analyze": "cross-env ANALYZE=true next build"
},
As I mentioned previously, cross-env allows us to set environment variables in our package.json file. In this case, we are setting ANALYZE to true. If you were using a Windows operating system and didn’t install cross-env, you’d get an error like the one shown below when running the above script:
Now, let’s test our code by running one of the following commands:
# npm
npm run analyze
# Yarn
yarn analyze
Running either of the above command results in the same action as running the following:
ANALYZE=true npm run build
Conclusion
In this article, we discussed what a Next.js bundle is and investigated how bundle size can impact website performance. We also demonstrated how to use the @next/bundle-analyzer package to analyze and inspect bundles in a Next.js application. We saw how to inspect the bundles in the terminal, in the browser, and also using the tool’s sidebar filter.
The post How to analyze your Next.js app bundles appeared first on LogRocket Blog.