Reza Safari Blog
Published on

How to analyze Next.js app bundles?

Sometimes, it happens that our app performs slowly without any apparent reason, and even though we don't load heavy content, the pages still have a large size. It's even possible that, without being aware of it, a simple "hello world" app could exceed 2 megabytes in size, and many developers might not be aware of this issue.

The best way to identify and address these problems is by analyzing the project's bundles.

First, install the required packages:

npm install --dev cross-env @next/bundle-analyzer

If you don't have a next.config.js file, create one in the root of your project and add the following code:

const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
});

module.exports = withBundleAnalyzer({});

Then, open the package.json file and add the following scripts in the "scripts" section:

npm run analyze

This will perform an initial analysis, and two browser pages will open for you.

One page represents the server bundle, and the other represents the client bundle.

You can easily review and identify any additional bundles being loaded on the server or the client side.

Next.js bundle analyzer