Optimization of JS Bundle in Next.js

Sanjeev Kumar
2 min readFeb 4, 2023

--

In this article, We will discuss how we can reduce the javascript bundle size in next.js.

Before discussing about the optimization techniques, we are discussing how we know which libraries are heavy in size. Which increases our bundle size.

For next.js, we can use @next/bundle-analyzer for analyse javascript bundle which libraries are making bundle heavy in size.

Walkthrough the documentation to understand the bundle analyzer tool.

Next.js provides several built-in optimizations for optimizing JavaScript bundles in your application. Here are some ways to optimize your Next.js JavaScript bundles:

  • > Lazy loading: Load only the components that are currently needed, reducing the initial bundle size. Load the library or component when it is actually used like on Button Click or on a Page Load. For Example: -
lazy loading an script when it is actually used

In given image above, we are loading the fresh chat script when an component actually mount on the screen. Fresh Chat is only using on a specific page. So, there is no need to load these libraries which are using only on a specific screens.

  • > Code splitting: Next.js automatically splits your code into smaller chunks, so that only the necessary code is loaded for each page.
  • > Dynamic imports: Import components and modules only when they are needed, improving load times.
    Read Documentation for know more about Dynamic Imports.
  • > Efficient caching: Next.js caches assets, components, and data on the client to reduce the amount of data that needs to be downloaded on subsequent page loads.
  • > Tree shaking: Next.js uses modern build tools like Webpack to remove unused code from your bundle, reducing its size.
  • > Use webp images instead of jpeg/png: webp images sizes are less than jpeg/png and having same quality. You can use different tools which are use to covert images online. For Example:
    1. Cloud Convert
    2. Convertio
    3. Tiny Img

By following these optimization techniques, you can significantly reduce the size of your Next.js JavaScript bundles and improve the performance of your application.

--

--