VOOZH about

URL: https://blog.logrocket.com/how-to-analyze-next-js-app-bundles/

⇱ How to analyze your Next.js app bundles - LogRocket Blog


2024-05-14
3089
#nextjs
Timonwa Akintokun
155588
107
👁 Image

See how LogRocket's Galileo AI surfaces the most severe issues for you

No signup required

Check it out

Editor’s note: This post was updated by Timonwa Akintokun on 14 May 2024 to cover advanced techniques for working with app bundles, such as manually tweaking webpack configurations for finer bundling control, adding information about how to open and inspecting bundle files, and exploring custom webpack configurations for optimizing bundling.

👁 How To Analyze Your Next.js App Bundles

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.

🚀 Sign up for The Replay newsletter

The Replay is a weekly newsletter for dev and engineering leaders.

Delivered once a week, it's your curated guide to the most important conversations around frontend dev, emerging AI tools, and the state of modern software.

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 @next/bundle-analyzer

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 the 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:

👁 Next.js Bundle Analyzer Example Terminal

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 at these different methods.

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.


Over 200k developers use LogRocket to create better digital experiences

👁 Image
Learn more →

The First Load JS bundle is all the code shared or used by the app pages at the 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 size of the pages upon 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:

👁 Next.js App Bundles Client Side

The second page, nodejs.html, displays all the bundles for the server side:

👁 Next.js App Bundles 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.

Interpreting the output of the bundle analyzer

  • Rectangles: Each rectangle represents a module or package. The size of a rectangle shows how large or tiny the module or package is compared to others in the bundle. So, the larger the rectangle, the larger its size is, and vice versa
  • Color grouping: Files or modules that are related are grouped by colors
  • Hovering: Hovering over any rectangle shows you the stats related to that module
  • Clicking: Clicking on a module zooms into it, allowing you to have a more detailed view, especially if it has many nested modules/files inside of it. Clicking on an empty space zooms you out
  • 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:

👁 Next.js Bundle Analyzer Example

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:

👁 Viewing Next.js Bundle Analyzer Hide Chunk Option

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:

👁 Viewing Next.js Bundle Analyzer Sidebar

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:

👁 Searching Next.js Analyzer Modules File Folder Phrase

Or, you can select an entry point for initial chunks (i.e., any of your app’s pages):

👁 Filter Next.js Bundle Analyzer Initial Chunks

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:

👁 Error Did Not Install Cross-Env

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

Advanced techniques for working with app bundles

Apart from using bundle analysis tools, there are some advanced techniques that you can use to optimize your Next.js app bundles. Let’s look at a few examples.

Customizing your webpack configurations in Next.js

Earlier in the article, we modified our Next.js config by adding @next/bundle-analyzer to our next.config.js file, which helped us to analyze our app bundles. We can also use it to modify our webpack settings by adding loaders, plugins, or other optimization configurations to the webpack. But before adding them, you must ensure that Next.js is not already handling such optimizations for you.

To customize the webpack configuration, just add the webpack property to your next.config.js file and pass your configurations on to it:

module.exports = {
 webpack: (config, { isServer }) => {
 if (!isServer) {
 config. optimization.splitChunks.cacheGroups = {
 vendor: {
 test: /[\\/]node_modules[\\/]/,
 name: 'vendors',
 chunks: 'all',
 },
 }
 }
 return config
 },
}

In the code snippet above, we are modifying our webpack configuration by splitting the vendor libraries into a separate chunk for the client-side bundle. This example shows you how you can customize the webpack to handle bundle sizes.

Code splitting to reduce load times

Code splitting is when you split your code into small chunks, which can then be loaded when needed. It is a very useful technique, especially in large applications, as it reduces the initial page load of your pages.

Next.js already does this for you, allowing only the necessary code needed to render the page to be loaded. However, you can also manually optimize your pages by using dynamic imports. Here is an example:

import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(() => import('../components/DynamicComponent'), {
 loading: () => <p>Loading...</p>,
});
export default function Page() {
 return <DynamicComponent />;
}

Here, the DynamicComponent will only be loaded when needed, so it doesn’t increase your page’s load time.

Replacing heavy libraries with lighter alternatives

You can also reduce the size of your app bundles by replacing heavy libraries with lighter ones. For example, if you were using moment.js to handle dates in your application, you might want to consider switching it to date-fns or day.js, which are smaller in size compared to moment.js.

Similarly, if you are using a library where you only need a single component but end up importing the entire library, it would be best just to import the particular module you need. For instance, instead of importing the whole lodash library, you can import only the necessary functions:

// Instead of this:
import _ from 'lodash';
// Do this:
import debounce from 'lodash/debounce';

This ensures that only the required library parts are included in your bundle, significantly reducing its size.

Using debugger to find issues in Next.js bundles

You can use the debugger statement to find issues in your bundle. Adding the debugger statement to your code allows you to debug your client-side code. When you start the server with npm run dev or yarn dev and the statement is called, the browser pauses code execution, allowing you to inspect the code up to that point in the browser’s DevTools.

To debug on the server side, you need to include the --inspect flag in your development script. You can do so by updating your package.json like so:

{
 "scripts": {
 "dev": "NODE_OPTIONS='--inspect' next dev"
 }
}

Then, start your development server again with npm run dev or yarn dev. It will show you something similar to this in your terminal:

👁 Our Terminal When Using The Debugger Statement

Next, open chrome://inspect in Chrome. You will see your Next.js application inside the Remote Target section. Click on Inspect to open it in a separate Chrome DevTools window:

👁 Details For The Chrome Inspect Page

Then, click on the Sources tab and inspect your app as you would on the client side:

👁 Sources Tab

You can use the Sources panel to set breakpoints, inspect variables, and step through your server-side code. This helps you identify and resolve issues within your bundle.

Optimizing app performance with bundle analysis

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 explore some tips you can use to identify issues using the bundle analysis report:

  • Spotting large dependencies: Inspect large modules to see which are third-party packages, then look for alternative packages that are smaller in size
  • Detecting duplicate code: If a library or module appears multiple times in the bundle, different versions of that library might be installed in your application. Cross-check and remove the version you are not using
  • Analyzing bundle size metrics: You should consider optimizing a module if the stat size of that module is large. A large parsed size can also affect the memory usage and performance of the app. A large gzipped size can affect the loading times of your pages
  • Identifying unused code: Tree shaking can remove unused code, but sometimes, there may be cases where you have unshakable codes. Inspect your analysis report to confirm that there is no unused code in your bundle and manually exclude any found by modifying the webpack config in your next.config.js for example
  • Utilizing source maps: Source maps like source-map-explorer can help you map your minified code back to its original source. This is useful for debugging errors where you have to identify the files contributing to the minified code

Consider this scenario where a Next.js app that was analyzed with the @next/bundle-analyzer tool and the following issues were identified:

  • Large image file sizes: This can slow down an app’s load speed
  • Duplicate npm packages: This will unnecessarily increase the app’s bundle size
  • Unused npm packages: This will contribute to the app’s bundle size and slow down its load speed
  • Heavy JavaScript files: Unoptimized JavaScript files will add to an app’s bundle size

To optimize the app’s performance, here are some possible ways to address the above issues:

Alternatives to @next/bundle-analyzer

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:

  • webpack-bundle-analyzer: This widely-used tool analyzes the bundle size of webpack-based applications, including Next.js. It generates interactive visualizations of the bundle size and composition, making it easy to identify which modules take up the most space
  • next-bundle-analyzer: This community-driven alternative to the official @next/bundle-analyzer package provides similar functionality but with customized reports specifically for Next.js users
  • source-map-explorer: This popular tool analyzes the bundle size of an app by examining the source maps generated during the build process. It provides a treemap visualization of the bundle size and identifies where each byte of code is coming from
  • Statoscope: This web-based tool analyzes the size and composition of webpack bundles. It provides a simple interface for users to upload webpack stats files and generate visualizations that help identify which modules and dependencies contribute most to the app’s bundle size

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 fits your needs.

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 the bundles in various ways, such as in the terminal, the browser, and the tool’s sidebar filter.

Additionally, we covered some advanced techniques for working with app bundles, like customizing webpack configurations, implementing code splitting, and replacing heavy libraries with lighter alternatives, along with some tips and tricks you can implement when inspecting your bundle analysis for issues and improving performance.

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: Full visibility into production Next.js apps

Debugging Next applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket captures console logs, errors, network requests, and pixel-perfect DOM recordings from user sessions and lets you replay them as users saw it, eliminating guesswork around why bugs happen — compatible with all frameworks.

LogRocket's Galileo AI watches sessions for you, instantly identifying and explaining user struggles with automated monitoring of your entire product experience.

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.

👁 Image
👁 LogRocket Dashboard Free Trial Banner

Modernize how you debug your Next.js apps — start monitoring for free.

👁 Image
👁 Image
👁 Image

Stop guessing about your digital experience with LogRocket

Get started for free

Recent posts:

What is TSRX?: What JSX would look like if it were designed today

TSRX adds first-class control flow, conditional hooks, and scoped styles to React via a TypeScript compiler extension — no new framework required.

👁 Image
Ikeh Akinyemi
Jun 12, 2026 ⋅ 6 min read

How to add authentication to a React Native app with Better Auth

Learn how to build a full React Native auth system using Better Auth and Expo — with email/password login, Google OAuth, session persistence, and protected routes.

👁 Image
Chinwike Maduabuchi
Jun 9, 2026 ⋅ 13 min read

AI dev tool power rankings & comparison [June 2026]

Compare the top AI development tools and models of June 2026. View updated rankings, feature breakdowns, and find the best fit for you.

👁 Image
Chizaram Ken
Jun 8, 2026 ⋅ 11 min read

How to check username availability at scale with Bloom filters

Learn how Bloom filters reduce database lookups for username availability checks while preserving correctness at scale.

👁 Image
Rosario De Chiara
Jun 8, 2026 ⋅ 6 min read
View all posts

Would you be interested in joining LogRocket's developer community?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Sign up now