Serving React App with Incorrect publicPath
Issues
When your React app’s publicPath
is misconfigured, you’ll encounter problems with asset loading, routing, and general functionality. Here’s how to identify and fix these issues:
Symptoms of Incorrect publicPath
- Blank page with console errors about missing JS/CSS files
- 404 errors for static assets (images, fonts, etc.)
- Broken routing – Links don’t work or refresh causes 404s
- Incorrect API requests – Backend calls going to wrong URL
Fixes for Different Build Tools
Create React App (CRA) Solution
// package.json
{
"homepage": ".", // For relative paths (same directory)
"homepage": "/subfolder/", // For subdirectory deployments
"homepage": "https://yourdomain.com", // For absolute URLs
}
Webpack Configuration (ejected CRA or custom config)
// webpack.config.js
module.exports = {
output: {
publicPath: '/', // Default - root domain
publicPath: '/my-app/', // For subdirectory
publicPath: process.env.PUBLIC_URL || '/', // Dynamic
}
}
Vite Configuration
// vite.config.js
export default defineConfig({
base: '/', // Root domain
base: '/subdir/', // Subdirectory
base: process.env.BASE_PATH || '/', // Environment-based
})
Environment-Specific Solutions
- GitHub Pages (project site in subdirectory):
{
"homepage": "https://username.github.io/repo-name",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build -b gh-pages"
}
}
- Docker/Nginx:
location /subpath/ {
alias /usr/share/nginx/html/;
try_files $uri $uri/ /subpath/index.html;
}
- Netlify/Vercel:
- Set
PUBLIC_URL
environment variable - Configure “Base directory” in build settings
Testing Locally Before Deployment
# For subdirectory testing
npx serve -s build -l 3000 --single
# Or with custom path
PUBLIC_URL=/my-app/ npm start
Common Fixes for Dynamic Imports
// Change this:
import('./module').then(...)
// To this when using subpaths:
import(/* webpackPublicPath: '/my-app/' */ './module').then(...)
Remember to:
- Clear browser cache after changes
- Verify
build
folder structure matches expected paths - Check network tab in devtools for 404 errors
- Test both development and production builds