Serving React app from incorrect path

Loading

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

  1. Blank white screen on page load
  2. Missing CSS/styles
  3. JavaScript files failing to load (404 errors)
  4. Broken images and assets
  5. 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

  1. After building, check build/index.html:
  • All asset paths should start with /your-subpath/static/
  1. 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

  1. Always hard refresh (Ctrl+F5) after deployment
  2. Check browser console for 404 errors
  3. Verify the basename matches your subpath exactly
  4. Ensure trailing slashes are consistent
  5. Test with simple paths first before complex routing

Remember that proper subpath deployment requires coordination between:

  1. Your React build configuration
  2. Your routing setup
  3. Your web server configuration
  4. Any asset references in your code

Leave a Reply

Your email address will not be published. Required fields are marked *