Skip to main content

Overview

Deploying a React application involves building an optimized production bundle and hosting it on a static file server or CDN.
This guide covers deployment using Firebase Hosting, but the build concepts apply to any hosting platform.

Production Build

Create an optimized production build of your React application:
npm run build
The build command uses Create React App’s build script which:
  • Minifies JavaScript and CSS
  • Optimizes images and assets
  • Creates a production-ready bundle in the build directory
  • Generates source maps for debugging

Build Configuration

Your package.json contains the build scripts:
{
  "name": "react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-router-dom": "^6.4.1",
    "react-scripts": "5.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}
The build script creates a production-optimized version of your app with code splitting, minification, and optimization enabled.

Firebase Hosting Setup

Install Firebase CLI

Install the Firebase command-line tools globally:
npm install -g firebase-tools

Login to Firebase

Authenticate with your Google account:
firebase login

Initialize Firebase Project

Initialize Firebase in your project directory:
firebase init
1

Select Hosting

Choose “Hosting: Configure files for Firebase Hosting” from the features list.
2

Select Project

Select an existing Firebase project or create a new one.
3

Configure Settings

  • Set public directory to build
  • Configure as single-page app: Yes
  • Set up automatic builds with GitHub: Optional

Firebase Configuration Files

firebase.json

Configure Firebase Hosting behavior:
{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}
  • public: Directory to deploy (the build output folder)
  • ignore: Files to exclude from deployment
  • rewrites: Redirect all requests to index.html for client-side routing
The rewrite rule ensures all routes are handled by your React app, not the server. This is essential for React Router to work correctly in production.

.firebaserc

Store your Firebase project configuration:
{
  "projects": {
    "default": "<your-firebase-project-id>"
  }
}
Replace <your-firebase-project-id> with your actual Firebase project ID from the Firebase Console.

Deployment Process

Build and Deploy

1

Build Production Bundle

npm run build
This creates the optimized production files in the build directory.
2

Deploy to Firebase

firebase deploy
Uploads your build directory to Firebase Hosting.
3

View Your Site

Firebase provides a hosting URL:
https://your-project-id.web.app

Environment Variables

Manage environment-specific configuration:
REACT_APP_API_URL=http://localhost:8080
REACT_APP_ENV=development
Create React App requires environment variables to be prefixed with REACT_APP_ to be accessible in your code.

Using Environment Variables

const API_URL = process.env.REACT_APP_API_URL;

export async function fetchEvents() {
  const response = await fetch(`${API_URL}/events`);
  
  if (!response.ok) {
    throw new Error('Failed to fetch events');
  }
  
  return response.json();
}
Never commit .env.production files containing sensitive keys to version control. Use Firebase environment configuration or CI/CD secrets instead.

Custom Domain Setup

Connect a custom domain to your Firebase hosting:
firebase hosting:channel:deploy production
1

Add Custom Domain

Go to Firebase Console > Hosting > Add custom domain
2

Verify Ownership

Add the provided TXT record to your domain’s DNS settings
3

Configure DNS

Add the A records provided by Firebase to point your domain to Firebase Hosting
4

SSL Certificate

Firebase automatically provisions SSL certificates for HTTPS

Other Hosting Options

Vercel

npm i -g vercel
vercel
Automatic deployments from Git with zero configuration.

Netlify

npm install -g netlify-cli
netlify deploy
Continuous deployment with Git integration.

AWS S3 + CloudFront

aws s3 sync build/ s3://bucket-name
Scalable hosting with AWS infrastructure.

GitHub Pages

npm install gh-pages
npm run deploy
Free hosting for open-source projects.

Build Optimization

React automatically splits your code using dynamic imports:
import { lazy, Suspense } from 'react';

const EventsPage = lazy(() => import('./pages/Events'));

function App() {
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <EventsPage />
    </Suspense>
  );
}
Optimize images before building:
  • Use WebP format for images
  • Compress images with tools like ImageOptim
  • Lazy load images below the fold
Analyze your bundle size:
npm install --save-dev webpack-bundle-analyzer
"scripts": {
  "analyze": "source-map-explorer 'build/static/js/*.js'"
}

Performance Best Practices

1

Enable Compression

Ensure your hosting platform serves gzipped or brotli-compressed files.
2

Configure Caching

Set appropriate cache headers for static assets:
"headers": [
  {
    "source": "/static/**",
    "headers": [
      {
        "key": "Cache-Control",
        "value": "public, max-age=31536000, immutable"
      }
    ]
  }
]
3

Use CDN

Host assets on a CDN for faster global delivery.

CI/CD Integration

Automate deployments with GitHub Actions:
name: Deploy to Firebase

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Install dependencies
        run: npm ci
      
      - name: Build
        run: npm run build
      
      - name: Deploy to Firebase
        uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: '${{ secrets.GITHUB_TOKEN }}'
          firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
          channelId: live
          projectId: your-project-id

Monitoring and Analytics

Performance Monitoring

Add Firebase Performance Monitoring:
import { getPerformance } from 'firebase/performance';
const perf = getPerformance(app);

Error Tracking

Integrate error tracking:
npm install @sentry/react

Troubleshooting

Ensure your hosting platform redirects all routes to index.html. Check the rewrites configuration in firebase.json.
  • Verify variables are prefixed with REACT_APP_
  • Rebuild after changing environment variables
  • Check that .env files are in the project root
  • Analyze bundle with webpack-bundle-analyzer
  • Implement code splitting
  • Remove unused dependencies
  • Use tree-shaking effectively

Routing

Ensure client-side routing works in production

Authentication

Secure your deployed application

Build docs developers (and LLMs) love