DEV Community

Cover image for Exploring the NextJS bundle analyzer
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Exploring the NextJS bundle analyzer

Did you know that Next.js gives us an option to analyze our output bundle size?

While creating our application, it's hard to determine what will be included in the final build output.

But no worries, I'll show you how you can add the bundle analyzer to analyze the build output in this article.

Installing the Next.js bundle analyzer

First, let's take an existing Next.js project to work on.
I will use my Next markdown blog for this.

The first thing we want to do is install the analyzer with the following command.

npm install @next/bundle-analyzer
Enter fullscreen mode Exit fullscreen mode

The next part is to create/modify our next.config.js file.

The first element we need is a definition of the analyzer, which we can import like this.

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});
Enter fullscreen mode Exit fullscreen mode

The following step might depend on the fact that you already have some configuration.

If not, you can do the following export.

module.exports = withBundleAnalyzer({});
Enter fullscreen mode Exit fullscreen mode

Otherwise, you have to wrap your existing export with the bundle analyzer.

module.exports = withBundleAnalyzer({
  reactStrictMode: true,
});
Enter fullscreen mode Exit fullscreen mode

Running the analyzer

To run the analyzer, we have to use the environment variable defined above.

The command would look like this:

ANALYZE=true npm run build
Enter fullscreen mode Exit fullscreen mode

When you run this command, it will automatically open two pages in your browser.

  • The client-side code
  • The server-side code

Next.js client side bundle analyzer
Next.js server side bundle analyzer

You can quickly inspect what takes up the most space, or when using a Monorepos, which packages might have been included twice unintentionally.

Quick command

We can also create a quick command, so we don't have to worry about setting this environment variable on every call.

Head over to your package.json file and add a new script like this.

"scripts": {
    ...
    "analyze": "ANALYZE=true next build"
},
Enter fullscreen mode Exit fullscreen mode

Now you can quickly run the analyzer with the following command.

npm run analyze
Enter fullscreen mode Exit fullscreen mode

I've also uploaded the changes to the project so you can view them on GitHub.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
arndom profile image
Nabil Alamin

thanks, just what I needed at the moment

Collapse
 
dailydevtips1 profile image
Chris Bongers

Awesome! Hope it helps 💖