Forgetting to set homepage in package.json for static hosting

Loading

Forgetting to configure the homepage field in package.json is a common oversight that can break deployments to static hosting services like GitHub Pages, Netlify, or Vercel.

The Problem

When your React app isn’t hosted at the domain root (e.g., https://username.github.io/repo-name/), you’ll encounter:

  • Broken asset paths (404 errors for JS/CSS files)
  • Failed routing/navigation
  • Blank pages or styling issues
  • Incorrect API request paths

Solution: Configuring package.json

1. Basic Homepage Configuration

{
  "name": "my-app",
  "homepage": "https://username.github.io/repo-name",
  "version": "0.1.0",
  // ... other fields
}

2. For Create React App (CRA) Projects

CRA automatically uses this field to:

  • Set the base URL in generated HTML
  • Properly prefix asset paths
  • Configure the router basename (if using React Router)

3. Dynamic Configuration Options

For different environments:

{
  "homepage": {
    "production": "https://example.com",
    "staging": "https://staging.example.com",
    "development": ""
  }
}

Using environment variables:

{
  "homepage": "%REACT_APP_HOMEPAGE%"
}

Then set in .env:

REACT_APP_HOMEPAGE=https://username.github.io/repo-name

Deployment-Specific Examples

GitHub Pages

{
  "homepage": "https://username.github.io/repo-name",
  "scripts": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  }
}

Netlify/Vercel

{
  "homepage": "https://your-custom-domain.com",
  // Or for preview deployments:
  "homepage": "https://random-string.netlify.app"
}

Additional Configuration

1. React Router Setup

<BrowserRouter basename={process.env.PUBLIC_URL}>
  {/* Your routes */}
</BrowserRouter>

2. Manual Path References

When making API calls or referencing assets:

const apiUrl = process.env.PUBLIC_URL + '/api/data';
const imagePath = process.env.PUBLIC_URL + '/images/logo.png';

Troubleshooting

Common issues and fixes:

  1. Blank page on deployment:
  • Verify homepage URL is correct
  • Check console for 404 errors on assets
  1. Routing doesn’t work:
  • Ensure React Router has basename set
  • Configure server to serve index.html for all paths
  1. Mixed content warnings:
  • Use HTTPS URLs in homepage field
  • Set "homepage": "." for relative paths

Best Practices

  1. Set homepage early in project development
  2. Test locally using the build folder:
   serve -s build
  1. Use environment variables for different deployment targets
  2. Document the setup in your README.md
  3. Verify asset paths in the built index.html

Leave a Reply

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