Fixing Incorrect publicPath in React Applications
When your React application isn’t loading properly due to incorrect publicPath
configuration, assets (JS, CSS, images) fail to load because the browser can’t locate them at the expected URLs. Here’s how to diagnose and fix this issue.
Symptoms of Incorrect publicPath
- Blank white screen on deployment
- Console errors showing 404s for bundle files
- Styles not applying properly
- Images and fonts failing to load
- Routing working in development but broken in production
Solutions by Build Tool
1. Create React App (CRA)
Option A: Set homepage in package.json
{
"homepage": "https://yourdomain.com/your-app",
// or for subpath:
"homepage": "/your-app/"
}
Option B: Use environment variable
PUBLIC_URL=/your-app/ npm run build
2. Webpack Configuration
In webpack.config.js:
module.exports = {
output: {
publicPath: '/your-app/', // For subdirectory deployment
// or for root domain:
publicPath: '/'
}
}
3. Vite Configuration
In vite.config.js:
export default defineConfig({
base: '/your-app/', // For subdirectory deployment
// or for root domain:
base: '/'
})
4. Next.js Configuration
In next.config.js:
module.exports = {
basePath: '/your-app', // For subdirectory deployment
assetPrefix: '/your-app/' // For CDN or custom domain
}
Special Cases
1. GitHub Pages Deployment
{
"homepage": "https://username.github.io/repo-name",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}
2. Serving from a Subdirectory
// For React Router
<BrowserRouter basename="/your-app">
3. Dynamic publicPath (Advanced)
// webpack.config.js
module.exports = {
output: {
publicPath: process.env.ASSET_PATH || '/',
}
}
Verification Steps
- After building, check
build/index.html
:
- Script src paths should match your deployment structure
<link>
href paths should be correct
- Inspect network requests in browser DevTools:
- Verify assets are loading from expected paths
- Test locally before deploying:
serve -s build -l 3000
Common Fixes for Specific Errors
Error: “Unexpected token <” in main.chunk.js
This usually means the JS file wasn’t found and the server returned HTML instead.
Solution:
// webpack.config.js
publicPath: '/'
Error: White screen with manifest.json 404
{
"start_url": "./",
"scope": "./"
}
Best Practices
- Test locally first with
serve
or similar tool - Use relative paths for maximum compatibility
- Set up redirects on your server for client-side routing
- Version your assets to prevent caching issues
- Document your deployment structure for team members
Server Configuration Examples
Nginx Configuration
location /your-app/ {
try_files $uri $uri/ /your-app/index.html;
}
Netlify _redirects
/* /index.html 200
By properly configuring publicPath
and understanding how it affects your asset loading, you can ensure your React application deploys correctly to any environment. Always verify your configuration matches your actual deployment structure.