Forgetting to set homepage in package.json for static hosting

Loading

Forgetting to Set Homepage in package.json for Static Hosting

When deploying a React app (or similar frontend project) to static hosting services like GitHub Pages, Netlify, or Vercel, forgetting to set the homepage field in package.json can cause several issues:

Common Problems Without Homepage Setting

  1. Broken asset paths – Images, CSS, and JS files won’t load properly
  2. 404 errors on refresh – Routing fails when not at the root domain
  3. Incorrect base URL – API requests and links may point to wrong locations

How to Fix It

1. For Create React App (CRA) projects:

// package.json
{
  "name": "my-app",
  "homepage": "https://yourusername.github.io/your-repo-name",
  // or for custom domains:
  "homepage": "https://yourdomain.com",
  // or for subdirectory deployments:
  "homepage": "https://yourdomain.com/subdir",
}

2. For Vite projects:

// vite.config.js
export default defineConfig({
  base: '/your-repo-name/', // for GitHub Pages
  // or for custom domain:
  base: '/',
})

3. For Next.js projects:

// next.config.js
module.exports = {
  basePath: '/your-repo-name', // if deploying to subdirectory
  assetPrefix: '/your-repo-name/', // for static assets
}

Additional Configuration Needed

  1. For React Router:
   <BrowserRouter basename="/your-repo-name">
  1. For asset imports:
   // Use process.env.PUBLIC_URL for assets
   <img src={`${process.env.PUBLIC_URL}/logo.png`} />

Deployment Tips

  1. GitHub Pages:
   npm install --save-dev gh-pages
   # Then add these scripts:
   "scripts": {
     "predeploy": "npm run build",
     "deploy": "gh-pages -d build"
   }
  1. Netlify/Vercel:
  • These platforms usually detect settings automatically
  • May need to set “Base directory” in build settings for subdirectory deployments

Remember to rebuild and redeploy your app after making these changes!

Leave a Reply

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