Back to list
Create React app not at /

Create React app not at /

How to configure create-react-app to live in a sub-folder.

By default, a React application (built with create-react-app) is made to be deployed at the root of a domain:

-> https://my.example.domain/

This is perfectly fine except that sometimes, you want it to live here:

-> https://my.example.domain/path/to/app

In that case, the application won't work anymore when published, although it works perfectly when running the dev server.

To make it work without adding any external package or ejecting from the tool, do the following.

You'll need to modify the package.json file and be a little flexible for the urls you use for subsequent API calls.

In the package.json, add the homepage attribute:

// ...
"homepage": "/path/to/app",
// ...

When building the final bundle, all the dependencies handled by webpack under the hood will use that value to be loaded.

Be aware that when running the application locally, it will not use that value! So "works on my machine" might be correct but as helpful as usual ;-).

If you rely on fetch calls on resources in the public folder (e.g. mocks), those will not work, you need to prepend process.env.PUBLIC_URL to all you URLs.

Another note, you probably are using a router so you'll also need to inform it that the base of the urls are relative to a prefix.

E.g. with react-router >v4:

<BrowserRouter basename={process.env.PUBLIC_URL}>{/* ... */}</BrowserRouter>

BONUS: If you're tired of npm start opening yet another tab, add BROWSER=NONE in a file named .env.