@@ -46,10 +46,7 @@ Depending on your needs, Next.js allows you to choose your data fetching strateg
## Migration Steps
Our goal with this migration is to get a working Next.js application as quickly as possible, so that
you can then adopt Next.js features incrementally. To begin with, we'll keep it as a purely
client-side application (SPA) without migrating your existing router. This helps minimize the
chances of encountering issues during the migration process and reduces merge conflicts.
Our goal with this migration is to get a working Next.js application as quickly as possible, so that you can then adopt Next.js features incrementally. To begin with, we'll keep it as a purely client-side application (SPA) without migrating your existing router. This helps minimize the chances of encountering issues during the migration process and reduces merge conflicts.
### Step 1: Install the Next.js Dependency
...
...
@@ -61,8 +58,7 @@ npm install next@latest
### Step 2: Create the Next.js Configuration File
Create a `next.config.mjs` at the root of your project. This file will hold your
Create a `next.config.mjs` at the root of your project. This file will hold your [Next.js configuration options](/docs/app/api-reference/next-config-js).
```js filename="next.config.mjs"
/** @type {import('next').NextConfig} */
...
...
@@ -74,8 +70,6 @@ const nextConfig = {
export default nextConfig
```
> **Good to know:** You can use either `.js` or `.mjs` for your Next.js configuration file.
### Step 3: Update TypeScript Configuration
If you're using TypeScript, you need to update your `tsconfig.json` file with the following changes to make it compatible with Next.js:
...
...
@@ -116,16 +110,11 @@ If you're using TypeScript, you need to update your `tsconfig.json` file with th
}
```
You can find more information about configuring TypeScript on the
You can find more information about configuring TypeScript on the [Next.js docs](/docs/app/building-your-application/configuring/typescript#typescript-plugin).
### Step 4: Create the Root Layout
A Next.js [App Router](/docs/app) application must include a
file, which is a [React Server Component](/docs/app/building-your-application/rendering/server-components)
that will wrap all pages in your application. This file is defined at the top level of the `app`
directory.
A Next.js [App Router](/docs/app) application must include a [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) file, which is a [React Server Component](/docs/app/building-your-application/rendering/server-components) that will wrap all pages in your application. This file is defined at the top level of the `app` directory.
The closest equivalent to the root layout file in a CRA application is the `index.html` file, which contains your `<html>`, `<head>`, and `<body>` tags.
...
...
@@ -152,8 +141,7 @@ export default function RootLayout({ children }) {
> **Good to know**: `.js`, `.jsx`, or `.tsx` extensions can be used for Layout files.
3. Copy the content of your `index.html` file into the previously created `<RootLayout>` component while
replacing the `body.div#root` and `body.script` tags with `<divid="root">{children}</div>`:
Copy the content of your `index.html` file into the previously created `<RootLayout>` component while replacing the `body.div#root` and `body.script` tags with `<divid="root">{children}</div>`:
```tsx filename="app/layout.tsx" switcher
export default function RootLayout({
...
...
@@ -199,10 +187,9 @@ export default function RootLayout({ children }) {
> **Good to know**: We'll ignore the [manifest file](/docs/app/api-reference/file-conventions/metadata), additional iconography other than the favicon, and [testing configuration](/docs/app/building-your-application/testing), but if these are requirements, Next.js also supports these options.
4. Next.js already includes by default the
[meta charset](https://developer.mozilla.org/docs/Web/HTML/Element/meta#charset) and
[meta viewport](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) tags, so you
can safely remove those from your `<head>`:
### Step 5: Metadata
Next.js already includes by default the [meta charset](https://developer.mozilla.org/docs/Web/HTML/Element/meta#charset) and [meta viewport](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) tags, so you can safely remove those from your `<head>`:
```tsx filename="app/layout.tsx" switcher
export default function RootLayout({
...
...
@@ -242,12 +229,7 @@ export default function RootLayout({ children }) {
}
```
5. Any [metadata files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata)
such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application
`<head>` tag as long as you have them placed into the top level of the `app` directory. After
into the `app` directory you can safely delete their `<link>` tags:
Any [metadata files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application `<head>` tag as long as you have them placed into the top level of the `app` directory. After moving [all supported files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) into the `app` directory you can safely delete their `<link>` tags:
```tsx filename="app/layout.tsx" switcher
export default function RootLayout({
...
...
@@ -285,10 +267,7 @@ export default function RootLayout({ children }) {
}
```
6. Finally, Next.js can manage your last `<head>` tags with the
[Metadata API](/docs/app/building-your-application/optimizing/metadata). Move your final metadata
Finally, Next.js can manage your last `<head>` tags with the [Metadata API](/docs/app/building-your-application/optimizing/metadata). Move your final metadata info into an exported [`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object):
```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next'
...
...
@@ -330,34 +309,51 @@ export default function RootLayout({ children }) {
}
```
With the above changes, you shifted from declaring everything in your `index.html` to using Next.js'
convention-based approach built into the framework
([Metadata API](/docs/app/building-your-application/optimizing/metadata)). This approach enables you
to more easily improve your SEO and web shareability of your pages.
With the above changes, you shifted from declaring everything in your `index.html` to using Next.js' convention-based approach built into the framework ([Metadata API](/docs/app/building-your-application/optimizing/metadata)). This approach enables you to more easily improve your SEO and web shareability of your pages.
### Step 6: Styles
Like Create React App, Next.js has built-in support for [CSS Modules](/docs/app/building-your-application/styling/css-modules).
If you're using a global CSS file, import it into your `app/layout.tsx` file:
```tsx filename="app/layout.tsx" switcher
import '../index.css'
// ...
```
If you're using Tailwind, you'll need to install `postcss` and `autoprefixer`:
```bash filename="Terminal"
npm install postcss autoprefixer
```
Then, create a `postcss.config.js` file at the root of your project:
### Step 5: Create the Entrypoint Page
```js filename="postcss.config.js"
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
```
On Next.js you declare an entrypoint for your application by creating a `page.tsx` file. The
closest equivalent of this file on CRA is your `src/index.tsx` file. In this step, you’ll set up the
entrypoint of your application.
### Step 7: Create the Entrypoint Page
1. **Create a `[[...slug]]` directory in your `app` directory.**
On Next.js you declare an entrypoint for your application by creating a `page.tsx` file. The closest equivalent of this file on CRA is your `src/index.tsx` file. In this step, you’ll set up the entry point of your application.
Since this guide is aiming to first set up our Next.js as an SPA (Single Page Application),
you need your page entrypoint to catch all possible routes of your application. For that, create a
new `[[...slug]]` directory in your `app` directory.
**Create a `[[...slug]]` directory in your `app` directory.**
[directories are used to define routes](/docs/app/building-your-application/routing/defining-routes#creating-routes).
This special directory will make sure that all routes of your application will be directed to its
containing `page.tsx` file.
Since this guide is aiming to first set up our Next.js as an SPA (Single Page Application), you need your page entry point to catch all possible routes of your application. For that, create a new `[[...slug]]` directory in your `app` directory.
2. **Create a new `page.tsx` file inside the `app/[[...slug]]` directory with the following content:**
This directory is what is called an [optional catch-all route segment](/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments). Next.js uses a file-system based router where [directories are used to define routes](/docs/app/building-your-application/routing/defining-routes#creating-routes). This special directory will make sure that all routes of your application will be directed to its containing `page.tsx` file.
**Create a new `page.tsx` file inside the `app/[[...slug]]` directory with the following content:**
@@ -380,8 +376,6 @@ export default function Page() {
}
```
> **Good to know**: `.js`, `.jsx`, or `.tsx` extensions can be used for Page files.
This file is a [Server Component](/docs/app/building-your-application/rendering/server-components). When you run `next build`, the file is prerendered into a static asset. It does _not_ require any dynamic code.
This file imports our global CSS and tells [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) we are only going to generate one route, the index route at `/`.
...
...
@@ -394,7 +388,7 @@ Now, let's move the rest of our CRA application which will run client-only.
This file is a [Client Component](/docs/app/building-your-application/rendering/client-components), defined by the `'use client'`
directive. Client Components are still [prerendered to HTML](/docs/app/building-your-application/rendering/client-components#how-are-client-components-rendered) on the server before being sent to the client.
This file is a [Client Component](/docs/app/building-your-application/rendering/client-components), defined by the `'use client'` directive. Client Components are still [prerendered to HTML](/docs/app/building-your-application/rendering/client-components#how-are-client-components-rendered) on the server before being sent to the client.
Since we want a client-only application to start, we can configure Next.js to disable prerendering from the `App` component down.
@@ -451,10 +444,9 @@ export default function Page() {
}
```
### Step 6: Update Static Image Imports
### Step 8: Update Static Image Imports
Next.js handles static image imports slightly different from CRA. With CRA, importing an image
file will return its public URL as a string:
Next.js handles static image imports slightly different from CRA. With CRA, importing an image file will return its public URL as a string:
```tsx filename="App.tsx"
import image from './img.png'
...
...
@@ -464,22 +456,13 @@ export default function App() {
}
```
With Next.js, static image imports return an object. The object can then be used directly with the
Next.js [`<Image>` component](/docs/app/api-reference/components/image), or you can use the object's
`src` property with your existing `<img>` tag.
With Next.js, static image imports return an object. The object can then be used directly with the Next.js [`<Image>` component](/docs/app/api-reference/components/image), 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](/docs/app/building-your-application/optimizing/images). The `<Image>`
component automatically sets the `width` and `height` attributes of the resulting `<img>` based on
the image's dimensions. This prevents layout shifts when the image loads. However, this can cause
issues if your app contains images with only one of their dimensions being styled without the other
styled to `auto`. When not styled to `auto`, the dimension will default to the `<img>` dimension
attribute's value, which can cause the image to appear distorted.
The `<Image>` component has the added benefits of [automatic image optimization](/docs/app/building-your-application/optimizing/images). The `<Image>` component automatically sets the `width` and `height` attributes of the resulting `<img>` based on the image's dimensions. This prevents layout shifts when the image loads. However, this can cause issues if your app contains images with only one of their dimensions being styled without the other styled to `auto`. When not styled to `auto`, the dimension will default to the `<img>` dimension attribute's value, which can cause the image to appear distorted.
Keeping the `<img>` tag will reduce the amount of changes in your application and prevent the above
issues. You can then optionally later migrate to the `<Image>` component to take advantage of optimizing images by [configuring a loader](/docs/app/building-your-application/optimizing/images#loaders), or moving to the default Next.js server which has automatic image optimization.
Keeping the `<img>` tag will reduce the amount of changes in your application and prevent the above issues. You can then optionally later migrate to the `<Image>` component to take advantage of optimizing images by [configuring a loader](/docs/app/building-your-application/optimizing/images#loaders), or moving to the default Next.js server which has automatic image optimization.
1. **Convert absolute import paths for images imported from `/public` into relative imports:**
**Convert absolute import paths for images imported from `/public` into relative imports:**
```tsx
// Before
...
...
@@ -489,7 +472,7 @@ import logo from '/logo.png'
import logo from '../public/logo.png'
```
2. **Pass the image `src` property instead of the whole image object to your `<img>` tag:**
**Pass the image `src` property instead of the whole image object to your `<img>` tag:**
```tsx
// Before
...
...
@@ -501,23 +484,17 @@ import logo from '../public/logo.png'
Alternatively, you can reference the public URL for the image asset based on the filename. For example, `public/logo.png` will serve the image at `/logo.png` for your application, which would be the `src` value.
> **Warning:** If you're using TypeScript, you might encounter type errors when accessing the `src`
> property. You can safely ignore those for now. They will be fixed by the end of this guide.
> **Warning:** If you're using TypeScript, you might encounter type errors when accessing the `src` property. You can safely ignore those for now. They will be fixed by the end of this guide.
Next.js has support for `.env` [environment variables](/docs/app/building-your-application/configuring/environment-variables) similar to CRA.
The main difference is the prefix used to expose environment variables on the
client-side. Change all environment variables with the `REACT_APP_` prefix to `NEXT_PUBLIC_`.
The main difference is the prefix used to expose environment variables on the client-side. Change all environment variables with the `REACT_APP_` prefix to `NEXT_PUBLIC_`.
### Step 8: Update Scripts in `package.json`
### Step 10: Update Scripts in `package.json`
You should now be able to run your application to test if you 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`:
You should now be able to run your application to test if you 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`, `next-env.d.ts`, and `dist` to your `.gitignore` file:
```json filename="package.json"
{
...
...
@@ -538,9 +515,7 @@ dist
Now run `npm run dev`, and open [`http://localhost:3000`](http://localhost:3000). You should see your application now running on Next.js.
> **Example:** Check out [this repository](https://github.com/vercel/cra-to-next) for a working example of a CRA application migrated to Next.js.
### Step 9: Clean Up
### Step 11: Clean Up
You can now clean up your codebase from Create React App related artifacts:
...
...
@@ -559,10 +534,7 @@ Further, Next.js has support for [Turbopack](/docs/app/api-reference/next-config
## Next Steps
If everything went according to plan, you now have a functioning Next.js application running as a
single-page application. However, you aren't yet taking advantage of most of Next.js' benefits, but
you can now start making incremental changes to reap all the benefits. Here's what you might want to
do next:
If everything went according to plan, you now have a functioning Next.js application running as a single-page application. However, you aren't yet taking advantage of most of Next.js' benefits, but you can now start making incremental changes to reap all the benefits. Here's what you might want to do next:
- Migrate from React Router to the [Next.js App Router](/docs/app/building-your-application/routing) to get: