Migrating from Vite to Next.js
Igor Gassmann · 7/20/2023 · 12 min read
After having recently redesigned the Inngest Dashboard with the Next.js App Router with great results, we decided to migrate our Dev Server app from Vite to Next.js to accommodate a new set of incoming features. To our surprise, we were able to do the migration in less than a day.
This article will guide you through how to migrate an existing Vite app to Next.js. But why would you want to switch to Next.js in the first place?
Why Switch?
Vite is loved by many within the React community for good reasons. It provides a great DX (Developer Experience), and it's easy to get started on. However, there are several reasons why you would want to switch to Next.js:
- Slow initial page loading time: If you have built your app with the default Vite plugin for React, your app is a purely client-side app. Client-side apps — also known as single-page applications (SPAs) — often suffer from a slow initial page loading time. This happens due to a couple of reasons:
- The browser needs to wait for the React code and your entire application bundle to download and run before your code is able to send requests to load some data.
- Your application code grows with every new feature and extra dependency you add.
- No automatic code splitting: The previous issue can be somewhat managed with code splitting. However, if you try to do code splitting manually, you'll often make performance worse. It's easy to inadvertently introduce network waterfalls when code-splitting manually. Next.js provides automatic code splitting built into its router, partly thanks to Server Components.
- Network waterfalls: A common cause of poor performance occurs when applications make sequential client-server requests to fetch data. One common pattern for data fetching in a SPA is to initially render a placeholder and then fetch data after the component has mounted. Unfortunately, this means that a child component that fetches data can't start fetching until the parent component finishes loading its own data resulting in slow loading times. On Next.js, this issue is resolved by fetching data in a Server Component.
- Fast and intentional loading states: Thanks to built-in support for Streaming with Suspense, with Next.js, you can be more intentional about which parts of your UI you want to load first and in what order without suffering from network waterfalls. This enables you to build pages that are faster to load and that don't introduce layout shifts.
- Choose the data fetching strategy: depending on your need, Next.js allows you to choose your data fetching strategy on a page and component basis. You can decide to fetch at build time, at request time on the server, or on the client. For example, you can fetch data from your CMS and render your blog posts at build time, which can then be efficiently cached on a CDN.
- Middleware: The Next.js middleware allows you to run code on the server before a request is completed. This is especially useful to avoid having a flash of unauthenticated content when the user visits an authenticated-only page by redirecting the user to a login page. The middleware is also useful for experimentation and internationalization.
- Support for Server Component: Unlike the current version of Vite, Next.js supports Server Components, which come with their own benefits.
- Built-in Optimizations: Next.js has built-in components for automatically optimizing images, fonts, and third-party scripts.
Migration Steps
Our goal with this migration is to get a working Next.js app as quickly as possible, so you can start to adopt Next.js features incrementally. To begin with, we'll keep it as a pure client-side app (SPA) without migrating your existing router. This helps minimize the chances of encountering errors and issues during the migration process and reduces merge conflicts.
Step 1: Install Next.js dependency
The first thing we need to do is to install next
as a dependency:
bashnpm install next
Step 2: Create the Next.js config file
Create a next.config.mjs
at the root of your project. This file will hold your Next.js configuration options.
jsx/** @type {import('next').NextConfig} */const nextConfig = {output: 'export', // Outputs a Single-Page Application (SPA)distDir: './dist', // Changes the output directory `./dist/`}export default nextConfig
Step 3: Update TypeScript configuration
We need to update your tsconfig.json
file with the following changes to make it compatible with Next.js:
- Remove the project reference to
tsconfig.node.json
- Add
./dist/types/**/*.ts
and./next-env.d.ts
to theinclude
array - Add
./node_modules
to theexclude
array - Add
{ "name": "next" }
to theplugins
array incompilerOptions
:"plugins": [{ "name": "next" }]
- Set
esModuleInterop
totrue
:"esModuleInterop": true
- Set
jsx
topreserve
:"jsx": "preserve"
- Set
allowJs
totrue
:"allowJs": true
- Set
forceConsistentCasingInFileNames
totrue
:"forceConsistentCasingInFileNames": true
- Set
incremental
totrue
:"incremental": true
Here's an example of a working tsconfig.json
file with those changes:
json{"compilerOptions": {"target": "ES2020","useDefineForClassFields": true,"lib": ["ES2020", "DOM", "DOM.Iterable"],"module": "ESNext","esModuleInterop": true,"skipLibCheck": true,"moduleResolution": "bundler","allowImportingTsExtensions": true,"resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"jsx": "preserve","strict": true,"noUnusedLocals": true,"noUnusedParameters": true,"noFallthroughCasesInSwitch": true,"allowJs": true,"forceConsistentCasingInFileNames": true,"incremental": true,"plugins": [{ "name": "next" }]},"include": ["./src", "./dist/types/**/*.ts", "./next-env.d.ts"],"exclude": ["./node_modules"]}
You can find more information about configuring TypeScript on the Next.js docs.
Step 4: Create the Root Layout
A Next.js App Router application must include a root layout file, which is a React Server Component that will wrap all pages in your app. This file is defined at the top level of the app
directory. The closest equivalent to the root layout file in a Vite app is the index.html
file, which contains your <html>
, <head>
, and <body>
tags.
In this step, we'll convert the index.html
file into a root layout file:
- Create a new
app
directory in yoursrc
directory. - Create a new
layout.tsx
file inside thatapp
directory:
tsxexport default function RootLayout({children,}: {children: React.ReactNode}) {return null;}
- Copy your
index.html
file content into the previously created<RootLayout>
component while replacing thebody.div#root
andbody.script
tags with<div id="root">{children}</div>
tsxexport default function RootLayout({children,}: {children: React.ReactNode}) {return (<html lang="en"><head><meta charset="UTF-8" /><link rel="icon" type="image/svg+xml" href="/icon.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>My App</title><meta name="description" content="My App is a..."></head><body><div id="root">{children}</div></body></html>)}
- Next.js already includes by default the meta charset and meta viewport tags, so you can safely remove those from your
<head>
.
tsxexport default function RootLayout({children,}: {children: React.ReactNode}) {return (<html lang="en"><head><link rel="icon" type="image/svg+xml" href="/icon.svg" /><title>My App</title><meta name="description" content="My App is a..."></head><body><div id="root">{children}</div></body></html>)}
- Any metadata files such as
favicon.ico
,icon.png
,robots.txt
are automatically added to the app<head>
tag as long as you have them to the top level of theapp
directory. After moving all supported files into theapp
directory you can safely delete their<link>
tags.
tsxexport default function RootLayout({children,}: {children: React.ReactNode}) {return (<html lang="en"><head><title>My App</title><meta name="description" content="My App is a..."></head><body><div id="root">{children}</div></body></html>)}
- Finally, Next.js can manage the last
<head>
tags with the Metadata API. Move your final metadata info into an exportedMetadata
object.
tsximport { Metadata } from 'next'export const metadata: Metadata = {title: 'My App',description: 'My App is a...',}export default function RootLayout({children,}: {children: React.ReactNode}) {return (<html lang="en"><body><div id="root">{children}</div></body></html>)}
With the above changes, we shifted from declaring everything in our index.html
to using Next.js' convention-based approach built into the framework (Metadata API). This approach enables you to more easily improve your SEO and web shareability of your pages.
Step 5: Create the Entrypoint Page
On Next.js you declare an entrypoint for your application by creating a page.tsx
file. The closest equivalent of this file on Vite is your main.tsx
file. In this step, we'll set up the entrypoint of your app.
-
Create a
[[...slug]]
directory in yourapp
directory.Since in this guide we're aiming first for setting up our Next.js as a pure SPA (Single Page Application), we need our page entrypoint to catch all possible routes of your app. For that, create a new
[[...slug]]
directory in yourapp
directory.This directory is what is called an optional catch-all route segment. Next.js uses a file-system based router where directories are used to define routes. This special directory will make sure that all routes of your app will be directed to its containing
page.tsx
file. -
Create a new
page.tsx
file inside the[[...slug]]
directory with the following content:tsx'use client'import dynamic from 'next/dynamic'import '../../index.css'const App = dynamic(() => import('../../App'), { ssr: false })export default function Page() {return (<App />)}This file contains a
<Page>
component which is declared as a Client Component by the'use client'
directive. Without that directive the component would have been a Server Component.On Next.js client components still get pre-rendered on the server (SSR) before being rendered on the client, but since we want to first have a pure client-side app, we need to tell Next.js to disable the pre-rendering for the
<App>
component by importing it with thessr
option set tofalse
:tsxconst App = dynamic(() => import('../../App'), { ssr: false })
Step 6: Update Static Image Imports
Next.js handles static image imports slightly different from Vite. With Vite, importing an image file will return its public URL as a string:
tsximport image from './img.png'// ...<img src={image} >
With Next.js, static image imports return an object. The object can then be used directly with the Next.js <Image>
component or you can use the object's src property with your existing <img>
tag.
The <Image>
component has the added benefits of automatic image optimization, but the width and height will be set automatically, so you'll need to visually ensure layout is correct for each image. Using the <img>
tag will reduce the amount of changes in your application and prevent any image sizing or layout issues, so that is the easiest incremental path forward:
tsx// 1. Convert absolute import paths for images imported from `/public` into relative importsimport logo from '/logo.png' // before// ⬇️ should now beimport logo from '../public/logo.png' // after// 2a. Pass the image `src` property instead of the whole image objectimport logo from '../public/logo.png'<img src={logo.src} />// 2b. Use the Next.js Image componentimport Image from 'next/image'import logo from '../public/logo.png'<Image src={logo} /> // Be sure to set height and width via CSS
Step 7: Migrate the Environment Variables
Next.js has support for .env
environment variables similar to Vite. The main difference is the prefix used to expose environment variables on the client-side.
- Change all environment variables with the
VITE_
prefix toNEXT_PUBLIC_
.
Vite exposes a few built-in environment variables on the special import.meta.env
object which aren't supported by Next.js. You need to update their usage as follow:
import.meta.env.MODE
⇒process.env.NODE_ENV
import.meta.env.PROD
⇒process.env.NODE_ENV === 'production'
import.meta.env.DEV
⇒process.env.NODE_ENV !== 'production'
import.meta.env.SSR
⇒typeof window !== 'undefined'
Next.js also doesn't provide a built-in BASE_URL
environment variable. However, you can still configure one, if you need it:
- Add the following to your
.env
file:
tsx// ...NEXT_PUBLIC_BASE_PATH=/some-base-path
- Set
basePath
toprocess.env.NEXT_PUBLIC_BASE_PATH
in yournext.config.cjs
file:
tsx/** @type {import('next').NextConfig} */const nextConfig = {output: 'export',distDir: './dist',basePath: process.env.NEXT_PUBLIC_BASE_PATH,}module.exports = nextConfig
- Update
import.meta.env.BASE_URL
usages toprocess.env.NEXT_PUBLIC_BASE_PATH
Step 8: Update Scripts in package.json
You should now be able to run your app to test if we successfully migrated to Next.js. But before that, you need to update your scripts
in your package.json
with Next.js related commands, and add .next
and next-env.d.ts
to your .gitignore
.
tsx"scripts": {"dev": "next dev","build": "next build","start": "next start"},
Now run npm run dev
, and open localhost:3000
. You should hopefully see your app now running on Next.js.
If your app follows a conventional Vite configuration, this is all you would need to do to have a working version of your app.
Step 9: Clean Up
You can now clean up your codebase from Vite related artifacts:
- Delete
main.tsx
- Delete
index.html
- Delete
vite-env.d.ts
- Delete
tsconfig.node.json
- Delete
vite.config.ts
- Uninstall Vite dependencies
What's Next?
If everything went according to plan, you now have a functioning Next.js app running as a single-page application. You aren't yet taking advantage of most of Next.js' benefits, but you can now start making incremental changes to your app to reap all the benefits. Here's what you might want to do next:
- Enable pre-rendering (SSR) of your app by first making sure to safely access Web APIs.
- Migrate from React Router to the Next.js App Router to get:
- Automatic code splitting
- Streaming Server Rendering
- Update your ESLint configuration to support Next.js rules
- Optimize your images with the
<Image>
component - Optimize your fonts with
next/font
- Optimize third-party scripts with the
<Script>
component
We will also be going through those changes ourselves in the Dev Server app that we just migrated to Next.js. You can follow along our progress on GitHub.
Let us know if you'd like to see us cover this or similar topics further - tweet at us: @inngest!
Help shape the future of Inngest
Ask questions, give feedback, and share feature requests
Join our Discord!