When deploying a React application to a subdirectory (like example.com/app/
instead of example.com
), incorrect configuration leads to broken assets and routing issues. Here’s how to properly serve your React app from any path.
Common Symptoms of Incorrect Path Serving
- Blank white screen on page load
- Missing CSS/styles
- JavaScript files failing to load (404 errors)
- Broken images and assets
- Routing failures when refreshing pages
Complete Solution for Subpath Deployment
1. Configure package.json
{
"homepage": "/your-subpath",
"scripts": {
"build": "PUBLIC_URL=/your-subpath react-scripts build",
"start": "PUBLIC_URL=/ react-scripts start"
}
}
2. Set Up React Router (if using)
import { BrowserRouter as Router } from 'react-router-dom';
function App() {
return (
<Router basename="/your-subpath">
{/* Your app components */}
</Router>
);
}
3. Web Server Configuration
For Nginx:
location /your-subpath/ {
alias /path/to/your/build/;
try_files $uri $uri/ /your-subpath/index.html;
}
For Apache:
Alias /your-subpath "/path/to/your/build"
<Directory "/path/to/your/build">
RewriteEngine On
RewriteBase /your-subpath/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /your-subpath/index.html [L]
</Directory>
4. Asset Handling in Components
// For static assets, use process.env.PUBLIC_URL
function MyComponent() {
return (
<img
src={`${process.env.PUBLIC_URL}/images/logo.png`}
alt="Logo"
/>
);
}
Development vs Production Setup
Development (local)
# No subpath needed
npm start
Production Build
# Build with your subpath
PUBLIC_URL=/your-subpath npm run build
# Or set it in package.json as shown above
npm run build
Verification Steps
- After building, check
build/index.html
:
- All asset paths should start with
/your-subpath/static/
- Test locally before deploying:
serve -s build -l 5000
Then visit http://localhost:5000/your-subpath
Advanced Configuration
For Create React App:
{
"homepage": ".",
"scripts": {
"build": "react-scripts build",
"deploy": "PUBLIC_URL=/your-subpath npm run build && rsync -av build/ server:/path/to/destination"
}
}
For Custom Webpack:
// webpack.config.js
module.exports = {
output: {
publicPath: '/your-subpath/'
}
};
Troubleshooting Tips
- Always hard refresh (Ctrl+F5) after deployment
- Check browser console for 404 errors
- Verify the
basename
matches your subpath exactly - Ensure trailing slashes are consistent
- Test with simple paths first before complex routing
Remember that proper subpath deployment requires coordination between:
- Your React build configuration
- Your routing setup
- Your web server configuration
- Any asset references in your code