Editor’s note: This post was updated on 25 April 2023 to include additional information about optimizing app performance with bundle analysis and to provide some alternatives to the @next/bundle-analyzer package.
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 demonstrate how to use the @next/bundle analyzer package to inspect your Next.js app bundles and talk about a few alternatives. Lastly, we’ll discuss how to use bundle analysis to improve Next.js app performance.
Jump ahead:
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.
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.
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.
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 })
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:
analyze
folder in your .next
folder inside your root directory and create three files: client.html
, nodejs.html
, and edge.html
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 maintainersAfter the bundle analyzer has run, you can start inspecting your 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.
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.
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:
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:
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):
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
Bundle analysis is an essential tool for optimizing app performance. It helps identify potential bottlenecks and areas for improving an app’s load speed and reducing its bundle size.
Let’s consider the scenario of a Next.js app that was analyzed with the @next/bundle-analyzer tool; the following issues were identified:
To optimize the app’s performance, here are some possible ways to address the above issues:
While @next/bundle-analyzer is a popular choice for analyzing the bundle size of a Next.js app, several other options are available. Here are some alternatives to consider:
These are just a few of the many options available for analyzing the bundle size of a Next.js app. Consider experimenting with different tools to find the one that best meets your needs.
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 the bundles in various ways, such as in the terminal, the browser, and the tool’s sidebar filter.
Through this analysis, you’ll identify potential bottlenecks, such as duplicated or unused npm packages and large image sizes. You’ll be able to optimize your app’s performance by reducing bundle size and improving load speed. Bundle analysis is a critical tool for any developer looking to optimize their Next.js application and enhance user experience.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your Next.js app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.
The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.
Modernize how you debug your Next.js apps — start monitoring for free.
Leptos is an amazing Rust web frontend framework that makes it easier to build scalable, performant apps with beautiful, declarative UIs.
Learn more about the 5 best JavaScript libraries for dealing with multidimensional arrays, such as ndarray, math.js, and NumJs.
We spoke with Dom about his approach to balancing innovation with handling tech debt and to learn how he stays current with technology.
Vite is a versatile, fast, lightweight build tool with an exceptional DX. Let’s explore when and why you should adopt Vite in your projects.