Vite and Next.js for Building Faster Web Apps

In this article, you will learn how to use Vite a popular build tool with Next js to fasten the application development process. You will also learn how to configure and tweak Vite in the Next js application to experience a lightening fast development process. What is Vite? Vite is one of the most popular…

By.

min read

In this article, you will learn how to use Vite a popular build tool with Next js to fasten the application development process. You will also learn how to configure and tweak Vite in the Next js application to experience a lightening fast development process.

What is Vite?

Vite is one of the most popular build tools that provides a faster development experience for various modern web applications. It helps to integrate lightning-fast Hot Module Replacement (HMR) strategy and optimize the build performance to a top-level by utilizing the ESBuild.

Next js together with Vite can help to achieve the following advances to your app development experience:

  • The application start-up becomes blazingly fast by introducing hot reloads using HMR techniques where only those parts are refreshed which are touched during development.
  • Helps to generate highly optimized static pages and management of assets for production.
  • Teams can quickly scale the applications as it grows in size.

 

How to Start Using Vite with Next js ?

Follow these quick steps to install and configure Vite in your Next Js application:

Step 1 – Create Next Js App

Step 2 – Install Required Packages

Step 3 – Configure Application

Step 4 – Update Existing Scripts

Step 5 – Advanced Optimization Techniques

 

 

Step 1 – Create Next Js App

First of all, let’s create a new Next js application by using the create-next-app command. We will add TypeScript support for our application.

npx create-next-app@latest --typescript my-vite-nextjs-app

 

Now move into the application directory:

cd my-vite-nextjs-app

 

We have a new Next.js project with TypeScript support.

 

Step 2 – Install Required Packages

Next, we will install Vite and its Next.js plugin:

npm install --save-dev vite @vitejs/plugin-react-refresh

 

Step 3 – Configure Application

Now we will add configuration in the next.config.js file which is available at the application root. We need to add this configuration to use the Vite plugin:

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,

  experimental: {
    appDir: true,
  },

  webpack: (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      // Fix deps that don't work with vite
      'stream': require.resolve('stream-browserify'),
      'zlib': require.resolve('browserify-zlib'),
      'util': require.resolve('util'),
    }

    // Important: return the modified config
    return config
  },
}

module.exports = nextConfig

The above configuration will enable the new app directory support and make some tweaks to get incompatible packages to work with Vite.

 

Step 4 – Update Existing Scripts

Finally, we can replace the default Next.js build script in package.json with Vite:

// package.json

"scripts": {
-  "dev": "next dev",
-  "build": "next build",
-  "start": "next start"
+  "dev": "vite",
+  "build": "tsc && vite build",
+  "start": "vite preview"
}

Now we have a Vite-powered Next.js app. Which will represent some of the key advantages:

  • Lightning-fast HMR during development
  • Optimized production build with esbuild
  • True server-side rendering with Next.js
  • Static site generation support
  • TypeScript support out of the box

 

Optimizing the Vite + Next.js Build

Let’s have a look at some advanced techniques to further optimize the build for production.

1 – Multi-Page App mode

Next js by default builds all the routes into a single server bundle or chunk. But for large apps, its always better to build each page as a separate chunk file.

To achieve this, we need to configure the next.config.js file as below:

// next.config.js
export default {
  experimental: {
    appDir: true,
  },

  output: 'standalone',

  webpack: (config) => {
    config.output.chunkFilename = 'static/chunks/[name].js'
    return config
  },
}

This will switch Next js to multiple page app mode and separate each page bundle into its own chunk file.  Vite will now generate a separate .js and .css file for each page or component that is async-loaded to avoid large monolithic bundles and load only the required resources as requested.

 

2 – Prefetching and Preloading

Next js also has built-in support for prefetching and preloading links which improve page transition performance:

// pages/index.js

import Link from 'next/link'

export default function Home() {
  return (
    <Link href="/about" prefetch={false}>
      About
    </Link>
  )
}

The prefetch prop tells Next.js whether to prefetch this link in the background. This can be used to prefetch certain pages conditionally.

We can also preload pages to prioritize fetching important resources sooner:

// components/Navbar.js

import Link from 'next/link'

function Navbar() {
  return (
    <nav>
      <Link href="/" preload>
        Home
      </Link>
      <Link href="/products">
        Products
      </Link>
    </nav>
  )
}

Vite automatically handles prefetching and preloading for modules it splits so Next.js routes can benefit from this.

 

3 – Compression

Vite can compress and minify assets using gzip or brotli during the build:

// vite.config.js

export default {
  build: {
    brotliSize: false,
    chunkSizeWarningLimit: 2000,
  },
}

This optimizes large pages and chunks above 2kb and serves them pre-compressed.

 

4 – Static Assets

Next js exports all static assets to the public folder, we can configure Vite to copy static assets there on build:

// vite.config.js

export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString()
          }
        },
      },
    },
    assetsDir: '.next/static',
  },
}

This splits vendor modules into separate chunks and outputs static assets into Next.js static folder.

 

5 – Type Checking

We can run the TypeScript compiler during the build to catch errors before deploying:

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    sourcemap: true, 
  },
})

This builds source maps for proper error reporting. Then update the tsconfig.json to enable full type checking on build.

{
  "compilerOptions": {
    "noEmit": false
  }
}

With these optimizations, our Vite + Next.js build is as fast and efficient as possible! The app starts instantly with Hot Module Replacement, then also produces a highly optimized production build performance.

 

Conclusion

We have implemented Vite in our Next js app and also discussed how to implement various features in Next js to further fasten the build performance and manage resource loading techniques like:

  • Multiple page loading
  • Lazy-loaded resources for pages
  • Prefetching and Preloading pages
  • Assets management

etc.

 

hope this will be helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *