How to deploy a react app to a subdirectory
Deploy a React App to a subdirectory - Step by Step Guide.
This situation may come many times during your career as a react developer. When there may be a need to deploy your react project/app/build into a subdirectory on the server.
Let's suppose you are using create-react-app and react-router v4+.
- Define App Homepage in package.json
- Set Basename in Router
- Make changes in .htaccess
- Make build and deploy
- Enjoy!
Complete code is available on GitHub - Clik to Download Code - GitHub
1. Define App Homepage
In package.json add homepage like below
{
"homepage": "https://domain-name.com/directory-name",
OR
"homepage": "/directory-name",
}
Example: - package.json
{
"name": "deploy-react-app-subdirectory",
"version": "0.1.0",
"private": true,
"homepage": "/myreactapp",
"dependencies": {
"@testing-library/jest-dom": "^5.12.0",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3",
"bootstrap": "^4.6.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
2. Set Basename in Router
<Router basename={'/directory-name'}>
</Router>
Example: - Router
<Router basename={'/myreactapp'}>
<Route exact path={`/`} component={Home} />
<Route path={`/about`} component={About} />
<Route path={`/contact`} component={Contact} />
</Router>
3. Make changes in .htaccess
Example: - .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /myreactapp/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /myreactapp/index.html [L]
</IfModule>
4. Make build and deploy
npm run build
5. Enjoy!
After this, deploy build to the sub-directory from where you want to run react app, Enjoy!
Note - Incase you are facing any issue
In your code update urls of all the router/links/href, etc. - `${process.env.PUBLIC_URL}`
Complete code is available on GitHub - Clik to Download Code - GitHub
You may also like - Learn to deploy your app (react.js) on Firebase Hosting (Free)