Correctly Configuring publicPath for React Applications
When serving React apps, an incorrect publicPath
can cause broken assets, failed loading, and routing issues. Here’s how to properly configure it for different deployment scenarios.
Understanding publicPath
publicPath
determines:
- Where your assets are served from
- How files are referenced in your built HTML/CSS
- The base URL for all your application’s assets
Common Symptoms of Incorrect publicPath
- Blank white screen in production
- 404 errors for JavaScript/CSS files
- Broken images and static assets
- Failed API requests
- Routing malfunctions
Configuration Solutions
1. Webpack Configuration (for custom setups)
// webpack.config.js
module.exports = {
output: {
publicPath: '/', // Default for root domain
publicPath: '/my-app/', // For subdirectory
publicPath: 'https://cdn.example.com/', // For CDN
}
}
2. Create React App Solutions
Option A: package.json homepage field
{
"homepage": "https://example.com/subdirectory"
}
Option B: Environment variables
# .env
PUBLIC_URL=/subdirectory
3. For Different Environments
Development:
publicPath: '/'
Production:
publicPath: process.env.PUBLIC_URL || '/'
Testing:
publicPath: './' // Relative paths
Deployment-Specific Configurations
GitHub Pages
{
"homepage": "https://username.github.io/repo-name",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}
Netlify/Vercel
// No special config needed for root deployments
// For preview deployments:
publicPath: process.env.PUBLIC_URL || '/'
AWS S3/CloudFront
publicPath: process.env.CDN_URL || '/'
Dynamic Path Resolution
For advanced scenarios:
// webpack.config.js
const publicPath = process.env.NODE_ENV === 'production'
? 'https://cdn.example.com/'
: '/';
module.exports = {
output: { publicPath }
}
Troubleshooting Techniques
- Inspect built index.html:
- Check if asset paths match your deployment structure
- Verify environment variables:
echo $PUBLIC_URL
- Test locally:
serve -s build --listen 5000
- Check network tab:
- Look for failed resource loading
Best Practices
- Set publicPath early in project setup
- Use environment variables for flexibility
- Test in staging before production
- Document your deployment requirements
- Consider using relative paths for more portable builds
Common Fixes for Specific Issues
Problem: Assets loading from wrong path
Solution:
publicPath: process.env.PUBLIC_URL || '/'
Problem: Routing breaks on refresh
Solution:
// webpack.config.js
publicPath: '/'
// plus proper server configuration to serve index.html for all routes
Problem: CDN assets not loading
Solution:
publicPath: 'https://your-cdn-url.com/'