How to Analyze Your Sitecore Next.js Bundle

Anton Tishchenko
Anton Tishchenko
Cover Image for How to Analyze Your Sitecore Next.js Bundle

The modern front-end development has a lot of magic. You use one set of tools and files which are packaged together in a bundle that is used by the browser. But, sometimes you need to review the results of all this magic. Because the smaller your bundle is, the better performance your website has. Probably, there is something big, that you don’t need.

Most probably, if you use Sitecore with Next.js then you use Webpack. Webpack is used together with Next.js. You may use Turbopack as well. And if you are then I envy you, because you are on the edge of technology. But, it is still in beta, and we will skip Turbopack in this article.

First of all, what is Webpack? Webpack is a module bundler. Webpack allows convenient development using metalanguages(SASS, SCSS, TypeScript, etc.), and modern web frameworks(Vue, Angular, etc.), and templates(Pug, markdown, PostCSS). And all your code is efficiently bundled together with support by the major part of browsers. You may choose convenient tools for development and don’t worry about getting everything together.

Installation

  1. We need @next/bundle-analyzer package npm install @next/bundle-analyzer
  2. Sitecore JSS uses the plugin-based Next.js configuration. That is why, we need to add a new plugin under next-config\plugins folder bundleAnalyzer.js.
  3. This file should contain:
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
  openAnalyzer: true,
})

module.exports = withBundleAnalyzer;

enabled property configures the way to define if the bundle analyzer should be turned on. It relies on the environment variable process.env.ANALYZE in the given example. But this condition can be any depending on your case. Also, you can hardcode it. openAnalyzer property configures if the analyzer results should be opened immediately after the build.

Usage

Now, when we build the website next time if ANALYZE environment variable is set to ‘true’ then we will get additional files in the .next\analyze folder that contain a ‘foam’ diagram of the content of our bundle. We may review it and optimize it by removing or replacing parts.

Sample