Taylor Bryant

September 2, 2019

Move files to the root of a Next.js project

Need to place a file like sitemap.xml in the root of your Next.js project? Here's one way to do it.

Update: As of v9.1, Next.js supports a public folder to define files to be mounted at the root of your application

Next.js is a framework built by ZEIT that allows you to easily build server-side rendered React applications. It provides automatic code splitting, simple client-side routing, and hot code reloading out of the box.

By default, Next.js only sets up routes based on files in the ./pages and ./static directories. This is sufficient in most cases, but Next.js doesn't provide a simple way to expose files like favicons or a sitemap at the root of your app. Keep reading for a simple way to move your files to the root of a Next.js project.

Add a script to your project

Create a file called move-files-to-root-directory.js in the root of your project. This script simply moves the files specified to the root directory.

const fs = require(`fs`).promises;

Promise.all(
  [`_redirects`, `sitemap.xml`].map(fileName =>
    fs.copyFile(`./${fileName}`, `./out/${fileName}`).then(() => fileName)
  )
).then(fileNames =>
  console.log(
    `The following files were copied to './out': ${JSON.stringify(fileNames)}`
  )
);

Add a script to your package.json

Add a script to your package.json. I called it post-export, but you can call it whatever you like.

// In your package.json
{
  ...
  "scripts": {
    ...
    "post-export": "node move-files-to-root-directory.js"
  }
  ...
}

Update your build command to use the script

Update your build command to include the new npm script.

For example, I host this website on Netlify. Before adding this script, my build command looked like:

npm run export

And after...

npm run export && npm run post-export