Migrating from Create React App

This guide will help you understand how to transition from an existing non-ejected Create React App project to Next.js. Migrating to Next.js will allow you to:

And more! Let’s walk through a series of steps to complete the migration.

Updating package.json and dependencies

The first step towards migrating to Next.js is to update package.json and dependencies. You should:

  • Remove react-scripts (but keep react and react-dom). If you’re using React Router, you can also remove react-router-dom.
  • Install next.
  • Add Next.js related commands to scripts. One is next dev, which runs a development server at localhost:3000. You should also add next build and next start for creating and starting a production build.

Here’s an example package.json:

  1. {
  2. "scripts": {
  3. "dev": "next dev",
  4. "build": "next build",
  5. "start": "next start"
  6. },
  7. "dependencies": {
  8. "next": "latest",
  9. "react": "latest",
  10. "react-dom": "latest"
  11. }
  12. }

Static Assets and Compiled Output

Create React App uses the public directory for the entry HTML file as well as static assets, but Next.js only uses it for static assets. When migrating from Create React App, the location of the public directory remains the same.

  • Move any images, fonts, or other static assets to public.
  • Convert index.html (the entry point of your application) to Next.js. Any <head> code should be moved to a custom _document.js. Any shared layout between all pages should be moved to a custom _app.js.
  • See Styling for CSS/Sass files.
  • Add .next to .gitignore.

Creating Routes & Linking

With Create React App, you’re likely using React Router. Instead of using a third-party library, Next.js includes its own file-system based routing.

  • Create a pages directory at the root of your project.
  • Then, move the src/App.js file to pages/index.js. This file is the index page of your Next.js application. Populate this file with code that is used to display the index route in your Create React App.
  • Convert all other Route components to new files in the pages directory.
  • For routes that require dynamic content (e.g. /blog/:slug), you can use Dynamic Routes with Next.js (e.g. pages/blog/[slug].js). The value of slug is accessible through a query parameter. For example, the route /blog/first-post would forward the query object { 'slug': 'first-post' } to pages/blog/[slug].js (learn more here).

For more information, see Migrating from React Router.

Styling

Next.js has built-in support for CSS, Sass and CSS-in-JS.

With Create React App, you can import .css files directly inside React components. Next.js allows you to do the same, but requires these files to be CSS Modules. For global styles, you’ll need a custom _app.js to add a global stylesheet.

Safely Accessing Web APIs

With client-side rendered applications (like Create React App), you can access window, localStorage, navigator, and other Web APIs out of the box.

Since Next.js uses pre-rendering, you’ll need to safely access those Web APIs only when you’re on the client-side. For example, the following code snippet will allow access to window only on the client-side.

  1. if (typeof window !== 'undefined') {
  2. // You now have access to `window`
  3. }

A recommended way of accessing Web APIs safely is by using the useEffect hook, which only executes client-side:

  1. import { useEffect } from 'react'
  2. useEffect(() => {
  3. // You now have access to `window`
  4. }, [])

Image Component and Image Optimization

Since version 10.0.0, Next.js has a built-in Image Component and Automatic Image Optimization.

The Next.js Image Component, next/image, is an extension of the HTML <img> element, evolved for the modern web.

The Automatic Image Optimization allows for resizing, optimizing, and serving images in modern formats like WebP when the browser supports it. This avoids shipping large images to devices with a smaller viewport. It also allows Next.js to automatically adopt future image formats and serve them to browsers that support those formats.

Instead of optimizing images at build time, Next.js optimizes images on-demand, as users request them. Your build times aren’t increased, whether shipping 10 images or 10 million images.

  1. import Image from 'next/image'
  2. export default function Home() {
  3. return (
  4. <>
  5. <h1>My Homepage</h1>
  6. <Image
  7. src="/me.png"
  8. alt="Picture of the author"
  9. width={500}
  10. height={500}
  11. />
  12. <p>Welcome to my homepage!</p>
  13. </>
  14. )
  15. }

Environment Variables

Next.js has support for .env Environment Variables similar to Create React App. 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_.
  • Server-side environment variables will be available at build-time and in API Routes.

Search Engine Optimization

Most Create React App examples use react-helmet to assist with adding meta tags for proper SEO. With Next.js, we use next/head to add meta tags to your <head /> element. For example, here’s an SEO component with Create React App:

  1. // src/components/seo.js
  2. import { Helmet } from 'react-helmet'
  3. export default function SEO({ description, title, siteTitle }) {
  4. return (
  5. <Helmet
  6. title={title}
  7. titleTemplate={siteTitle ? `%s | ${siteTitle}` : null}
  8. meta={[
  9. {
  10. name: `description`,
  11. content: description,
  12. },
  13. {
  14. property: `og:title`,
  15. content: title,
  16. },
  17. {
  18. property: `og:description`,
  19. content: description,
  20. },
  21. {
  22. property: `og:type`,
  23. content: `website`,
  24. },
  25. {
  26. name: `twitter:card`,
  27. content: `summary`,
  28. },
  29. {
  30. name: `twitter:creator`,
  31. content: twitter,
  32. },
  33. {
  34. name: `twitter:title`,
  35. content: title,
  36. },
  37. {
  38. name: `twitter:description`,
  39. content: description,
  40. },
  41. ]}
  42. />
  43. )
  44. }

And here’s the same example using Next.js.

  1. // src/components/seo.js
  2. import Head from 'next/head'
  3. export default function SEO({ description, title, siteTitle }) {
  4. return (
  5. <Head>
  6. <title>{`${title} | ${siteTitle}`}</title>
  7. <meta name="description" content={description} />
  8. <meta property="og:type" content="website" />
  9. <meta property="og:title" content={title} />
  10. <meta property="og:description" content={description} />
  11. <meta property="og:site_name" content={siteTitle} />
  12. <meta property="twitter:card" content="summary" />
  13. <meta property="twitter:creator" content={config.social.twitter} />
  14. <meta property="twitter:title" content={title} />
  15. <meta property="twitter:description" content={description} />
  16. </Head>
  17. )
  18. }

Single-Page App (SPA)

If you want to move your existing Create React App to Next.js and keep a Single-Page App, you can move your old application’s entry point to an Optional Catch-All Route named pages/[[...app]].js.

  1. // pages/[[...app]].js
  2. import { useState, useEffect } from 'react'
  3. import CreateReactAppEntryPoint from '../components/app'
  4. function App() {
  5. const [isMounted, setIsMounted] = useState(false)
  6. useEffect(() => {
  7. setIsMounted(true)
  8. }, [])
  9. if (!isMounted) {
  10. return null
  11. }
  12. return <CreateReactAppEntryPoint />
  13. }
  14. export default App

Ejected Create React App

If you’ve ejected Create React App, here are some things to consider:

  • If you have custom file loaders set up for CSS, Sass, or other assets, this is all built-in with Next.js.
  • If you’ve manually added new JavaScript features (e.g. Optional Chaining) or Polyfills, check to see what’s included by default with Next.js.
  • If you have a custom code splitting setup, you can remove that. Next.js has automatic code splitting on a per-page basis.
  • You can customize your PostCSS setup with Next.js without ejecting from the framework.
  • You should reference the default Babel config and Webpack config of Next.js to see what’s included by default.

Learn More

You can learn more about Next.js by completing our starter tutorial. If you have questions or if this guide didn’t work for you, feel free to reach out to our community on GitHub Discussions.