Subscribe

Exploring the NextJS bundle analyzer

✍️

Using the NextJS bundle analyzer to evaluate big packages

25 Jul, 2022 · 2 min read

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

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',
});

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({});

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

module.exports = withBundleAnalyzer({
  reactStrictMode: true,
});

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

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"
},

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

npm run analyze

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Next portfolio - Filter by category

30 Nov, 2022 · 5 min read

Next portfolio - Filter by category

A glance at Turbopack

17 Nov, 2022 · 3 min read

A glance at Turbopack

Join 2097 devs and subscribe to my newsletter