src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx
import { Steps, LinkCard, CardGrid } from '@astrojs/starlight/components';
import AstroJSXTabs from '/components/tabs/AstroJSXTabs.astro';
import PackageManagerTabs from '/components/tabs/PackageManagerTabs.astro';
Here are some key concepts and migration strategies to help you get started. Use the rest of our docs and our Discord community to keep going!
Next.js and Astro share some similarities that will help you migrate your project:
.astro files is similar to JSX. Writing Astro should feel familiar..jsx or .tsx extension.When you rebuild your Next.js site in Astro, you will notice some important differences:
Next.js is a React single-page app, and uses index.js as your project's root. Astro is a multi-page site, and index.astro is your home page.
.astro components are not written as exported functions that return page templating. Instead, you'll split your code into a "code fence" for your JavaScript and a body exclusively for the HTML you generate.
content-driven: Astro was designed to showcase your content and to allow you to opt-in to interactivity only as needed. An existing Next.js app might be built for high client-side interactivity and may require advanced Astro techniques to include items that are more challenging to replicate using .astro components, such as dashboards.
Each project migration will look different, but there are some common actions you will perform when converting from Next.js to Astro.
Use the create astro command for your package manager to launch Astro's CLI wizard or choose a community theme from the Astro Theme Showcase.
You can pass a --template argument to the create astro command to start a new Astro project with one of our official starters (e.g. docs, blog, portfolio). Or, you can start a new project from any existing Astro repository on GitHub.
# create a new project with an official example
npm create astro@latest -- --template <example-name>
```
</Fragment>
<Fragment slot="pnpm">
```shell
# launch the Astro CLI Wizard
pnpm create astro@latest
# create a new project with an official example
pnpm create astro@latest --template <example-name>
```
</Fragment>
<Fragment slot="yarn">
```shell
# launch the Astro CLI Wizard
yarn create astro@latest
# create a new project with an official example
yarn create astro@latest --template <example-name>
```
</Fragment>
Then, copy your existing Next project files over to your new Astro project in a separate folder outside of src.
:::tip Visit https://astro.new for the full list of official starter templates, and links for opening a new project in Firebase Studio, StackBlitz, or CodeSandbox. :::
You may find it useful to install some of Astro's optional integrations to use while converting your Next project to Astro:
@astrojs/react: to reuse some existing React UI components in your new Astro site, or keep writing with React components.
@astrojs/mdx: to bring existing MDX files from your Next project, or to use MDX in your new Astro site.
srcFollowing Astro's project structure:
<Steps> 1. **Keep** Next's `public/` folder untouched.Astro uses the `public/` directory for static assets, just like Next. There is no change needed to this folder, nor its contents.
2. Copy or Move Next's other files and folders (e.g. pages, styles etc.) into Astro's src/ folder as you rebuild your site, following Astro's project structure.
Like Next, Astro's `src/pages/` folder is a special folder used for file-based routing. All other folders are optional, and you can organize the contents of your `src/` folder any way you like. Other common folders in Astro projects include `src/layouts/`, `src/components`, `src/styles`, `src/scripts`.
Astro has a configuration file at the root of your project called astro.config.mjs. This is used only for configuring your Astro project and any installed integrations, including SSR adapters.
.astro filesHere are some tips for converting a Next .js component into a .astro component:
Use the returned JSX of the existing Next.js component function as the basis for your HTML template.
Change any Next or JSX syntax to Astro or to HTML web standards. This includes <Link>, <Script>, {children}, and className, for example.
Move any necessary JavaScript, including import statements, into a "code fence" (---). Note: JavaScript to conditionally render content is often written inside the HTML template directly in Astro.
Use Astro.props to access any additional props that were previously passed to your Next function.
Decide whether any imported components also need to be converted to Astro. With the official integration installed, you can use existing React components in your Astro file. But, you may want to convert them to .astro components, especially if they do not need to be interactive!
Replace getStaticProps() with import statements or import.meta.glob() to query your local files. Use fetch() to fetch external data.
See an example of a Next .js file converted step-by-step.
Compare the following Next component and a corresponding Astro component:
<AstroJSXTabs> <Fragment slot="jsx"> ```jsx title="StarCount.jsx" import Header from "./header"; import Footer from "./footer"; import "./layout.css";export async function getStaticProps() {
const res = await fetch("https://api.github.com/repos/withastro/astro");
const json = await res.json();
return {
props: { message: json.message, stars: json.stargazers_count || 0 },
}
}
const Component = ({ stars, message }) => {
return (
<>
<Header />
<p style={{
backgroundColor: `#f4f4f4`,
padding: `1em 1.5em`,
textAlign: `center`,
marginBottom: `1em`
}}>Astro has {stars} 🧑🚀</p>
<Footer />
</>
)
}
export default Component;
```
const res = await fetch("https://api.github.com/repos/withastro/astro");
const json = await res.json();
const message = json.message;
const stars = json.stargazers_count || 0;
---
<Header />
<p class="banner">Astro has {stars} 🧑🚀</p>
<Footer />
<style>
.banner {
background-color: #f4f4f4;
padding: 1em 1.5em;
text-align: center;
margin-bottom: 1em;
}
</style>
```
You may find it helpful to start by converting your Next.js layouts and templates into Astro layout components.
Next has two different methods for creating layout files, each of which handles layouts differently than Astro:
The pages directory
Each Astro page explicitly requires <html>, <head>, and <body> tags to be present, so it is common to reuse a layout file across pages. Astro uses a <slot /> for page content, with no import statement required. Note the standard HTML templating, and direct access to <head>:
---
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>Astro</title>
</head>
<body>
<!-- Wrap the slot element with your existing layout templating -->
<slot />
</body>
</html>
pages directoryYour Next project may have a pages/_document.jsx file that imports React components to customize your app's <head>:
import Document, { Html, Head, Main, NextScript } from "next/document";
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link rel="icon" href="/favicon.ico" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
Replace any React components with <html>, <head>, <slot>, and other HTML standard tags.
<html lang="en">
<head>
<link rel="icon" href="/favicon.ico" />
</head>
<body>
<slot/>
</body>
</html>
/app directoryNext.js' app/ directory layout files are created with two files: a layout.jsx file to customize the <html> and <body> contents, and a head.jsx file to customize the <head> element contents.
export default function Layout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
export default function Head() {
return (
<>
<title>My Page</title>
</>
);
}
Replace both these files with a single Astro layout file that contains a page shell (<html>, <head>, and <body> tags) and a <slot/> instead of React's {children} prop:
<html lang="en">
<head>
<title>My Page</title>
</head>
<body>
<slot/>
</body>
</html>
In Next.js, your posts either live in /pages or /app/routeName/page.jsx.
In Astro, all your page content must live within src/ unless you are using content collections.
Your existing Next JSX (.js) pages will need to be converted from JSX files to .astro pages. You cannot use an existing JSX page file in Astro.
These .astro pages must be located within src/pages/ and will have page routes generated automatically based on their file path.
Astro has built-in support for Markdown and an optional integration for MDX files. You can reuse any existing Markdown and MDX files, but they may require some adjustments to their frontmatter, such as adding Astro's special layout frontmatter property. You will no longer need to manually create pages for each Markdown-generated route. These files can be placed within src/pages/ to take advantage of automatic file-based routing.
Alternatively, you can use content collections in Astro to store and manage your content. You will retrieve the content yourself and generate those pages dynamically.
As Astro outputs raw HTML, it is possible to write end-to-end tests using the output of the build step. Any end-to-end tests written previously might work out-of-the-box if you have been able to match the markup of your Next site. Testing libraries such as Jest and React Testing Library can be imported and used in Astro to test your React components.
See Astro's testing guide for more.
Convert any Next <Link to="">, <NavLink> etc. components to HTML <a href=""> tags.
<Link to="/blog">Blog</Link>
<a href="/blog">Blog</a>
Astro does not use any special component for links, although you are welcome to build your own <Link> component. You can then import and use this <Link> just as you would any other component.
---
const { to } = Astro.props;
---
<a href={to}><slot /></a>
Update any file imports to reference relative file paths exactly. This can be done using import aliases, or by writing out a relative path in full.
Note that .astro and several other file types must be imported with their full file extension.
---
import Card from "../../components/Card.astro";
---
<Card />
Convert any instances of {children} to an Astro <slot />. Astro does not need to receive {children} as a function prop and will automatically render child content in a <slot />.
---
---
export default function MyComponent(props) {
return (
<div>
{props.children}
</div>
);
}
<div>
<slot />
</div>
React components that pass multiple sets of children can be migrated to an Astro component using named slots.
See more about specific <slot /> usage in Astro.
Convert any instances of getStaticProps() to either import.meta.glob() or getCollection()/getEntry() in order to access data from other files in your project source. To fetch remote data, use fetch().
These data requests are made in the frontmatter of the Astro component and use top-level await.
---
import { getCollection } from 'astro:content';
// Get all `src/content/blog/` entries
const allBlogPosts = await getCollection('blog');
// Get all `src/pages/posts/` entries
const allPosts = Object.values(import.meta.glob('../pages/posts/*.md', { eager: true }));
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
const randomUser = data.results[0];
---
See more about local files imports with import.meta.glob(), querying with content collections or fetching remote data.
You may need to replace any CSS-in-JS libraries (e.g. styled-components) with other available CSS options in Astro.
If necessary, convert any inline style objects (style={{ fontWeight: "bold" }}) to inline HTML style attributes (style="font-weight:bold;"). Or, use an Astro <style> tag for scoped CSS styles.
<div style={{backgroundColor: `#f4f4f4`, padding: `1em`}}>{message}</div>
<div style="background-color: #f4f4f4; padding: 1em;">{message}</div>
Tailwind is supported after installing the Tailwind Vite plugin. No changes to your existing Tailwind code are required!
See more about Styling in Astro.
Convert any Next <Image /> components to Astro's own image component in .astro or .mdx files, or to a standard HTML / JSX tag as appropriate in your React components.
Astro's <Image /> component works in .astro and .mdx files only. See a full list of its component attributes and note that several will differ from Next's attributes.
---
import { Image } from 'astro:assets';
import rocket from '../assets/rocket.png';
---
<Image src={rocket} alt="A rocketship in space." />
In React (.jsx) components, use standard JSX image syntax (``). Astro will not optimize these images, but you can install and use NPM packages for more flexibility.
You can learn more about using images in Astro in the Images Guide.
Here is an example of Next.js Pokédex data fetch converted to Astro.
pages/index.js fetches and displays a list of the first 151 Pokémon using the REST PokéAPI.
Here's how to recreate that in src/pages/index.astro, replacing getStaticProps() with fetch().
```jsx title="pages/index.js" {6-18}
import Link from 'next/link'
import styles from '../styles/poke-list.module.css';
export default function Home({ pokemons }) {
return (
<>
<ul className={`plain-list ${styles.pokeList}`}>
{pokemons.map((pokemon) => (
<li className={styles.pokemonListItem} key={pokemon.name}>
<Link className={styles.pokemonContainer} as={`/pokemon/${pokemon.name}`} href="/pokemon/[name]">
<p className={styles.pokemonId}>No. {pokemon.id}</p>
</img>
<h2 className={styles.pokemonName}>{pokemon.name}</h2>
</Link>
</li>
))}
</ul>
</>
)
}
export const getStaticProps = async () => {
const res = await fetch("https://pokeapi.co/api/v2/pokemon?limit=151")
const resJson = await res.json();
const pokemons = resJson.results.map(pokemon => {
const name = pokemon.name;
// https://pokeapi.co/api/v2/pokemon/1/
const url = pokemon.url;
const id = url.split("/")[url.split("/").length - 2];
return {
name,
url,
id
}
});
return {
props: {
pokemons,
},
}
}
```
2. Create src/pages/index.astro
Use the return value of the Next function. Convert any Next or React syntax to Astro, including changing the case of any [HTML global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes).
Note that:
- `.map` just works!
- `className` becomes `class`.
- `<Link>` becomes `<a>`.
- The `<> </>` fragment is not required in Astro templating.
- `key` is a React attribute, and is not an attribute of `li` in Astro.
```astro title="src/pages/index.astro" "class" "</a>" "<a"
---
---
<ul class="plain-list pokeList">
{pokemons.map((pokemon) => (
<li class="pokemonListItem">
<a class="pokemonContainer" href={`/pokemon/${pokemon.name}`}>
<p class="pokemonId">No. {pokemon.id}</p>
<h2 class="pokemonName">{pokemon.name}</h2>
</a>
</li>
))}
</ul>
```
3. Add any needed imports, props, and JavaScript
Note that:
- the `getStaticProps` function is no longer needed. Data from the API is fetched directly in the code fence.
- A `<Layout>` component is imported and wraps the page templating.
```astro ins={2,4-16,19,31} title="src/pages/index.astro"
---
import Layout from '../layouts/layout.astro';
const res = await fetch("https://pokeapi.co/api/v2/pokemon?limit=151");
const resJson = await res.json();
const pokemons = resJson.results.map(pokemon => {
const name = pokemon.name;
// https://pokeapi.co/api/v2/pokemon/1/
const url = pokemon.url;
const id = url.split("/")[url.split("/").length - 2];
return {
name,
url,
id
}
});
---
<Layout>
<ul class="plain-list pokeList">
{pokemons.map((pokemon) => (
<li class="pokemonListItem" key={pokemon.name}>
<a class="pokemonContainer" href={`/pokemon/${pokemon.name}`}>
<p class="pokemonId">No. {pokemon.id}</p>
<h2 class="pokemonName">{pokemon.name}</h2>
</a>
</li>
))}
</ul>
</Layout>
```
:::note[Have a resource to share?] If you found (or made!) a helpful video or blog post about converting a Next.js site to Astro, add it to this list! :::