Deploy React App To GitHub Pages With GitHub Actions

by Viktoria Ivanova 53 views

Hey guys! Today, we're diving deep into how to automatically deploy your React frontend to GitHub Pages using GitHub Actions. If you've ever struggled with manually deploying your frontend or just want a smoother, more automated workflow, you're in the right place. We’ll cover everything from setting up your GitHub Actions workflow to handling React Router compatibility and ensuring your assets load correctly. Let's get started!

Overview

The main goal here is to set up an automated deployment pipeline for our SPY-FLY React frontend using GitHub Actions. This means that whenever we push changes to our main branch, GitHub Actions will automatically build our frontend and deploy it to GitHub Pages. This not only saves us time but also ensures that our live site is always up-to-date with the latest changes. We’ll break down the process into manageable steps, making it easy to follow along.

Requirements

To make this happen, we have a few key requirements we need to tackle:

  1. Create a GitHub Actions workflow for automated deployment.
  2. Configure the frontend build process specifically for GitHub Pages deployment.
  3. Update React Router to ensure it works seamlessly with GitHub Pages.
  4. Set up a proper base URL configuration to handle routing correctly.
  5. Enable GitHub Pages in our repository settings.

Each of these steps is crucial, and we’ll go through them in detail to ensure everything works perfectly. So, stick with me!

Technical Details

Before we jump into the implementation, let's talk about some technical details. Our frontend is a React application built using Vite, which is a super-fast build tool and development server. It’s located in the /frontend directory of our repository. One of the challenges we'll face is handling client-side routing on GitHub Pages, as it doesn't behave like a traditional web server. Additionally, our API calls need to work with CORS (Cross-Origin Resource Sharing) from the GitHub Pages domain. We’ll address these issues as we go along.

Understanding the Tech Stack

First, let's break down why we're using React and Vite. React is a powerful JavaScript library for building user interfaces, known for its component-based architecture and efficient updates to the DOM. Vite, on the other hand, is a modern build tool that offers incredibly fast hot module replacement (HMR) and optimized builds. Together, they make for a fantastic development experience. However, deploying a single-page application (SPA) like this to GitHub Pages requires some specific configurations.

GitHub Pages serves static files directly from your repository. This means there's no backend server to handle routing. When a user navigates to a different route in your React app, it's all handled client-side by React Router. But when a user refreshes the page or tries to access a specific route directly, GitHub Pages needs to know how to serve the correct content. This is where the base URL and proper routing configuration come into play. This ensures a seamless user experience. Understanding these nuances is critical to a successful deployment.

CORS and API Calls

Another crucial aspect is handling CORS. CORS is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one which served the web page. When our frontend is deployed on GitHub Pages (e.g., https://carmandale.github.io/spy-fly/), and it tries to make API calls to a different domain (e.g., our backend API), the browser will enforce CORS. To make sure our API calls work, we need to configure our backend to allow requests from the GitHub Pages domain. This often involves setting the Access-Control-Allow-Origin header in the backend's responses. Configuring CORS correctly is paramount for the proper functioning of the application.

Acceptance Criteria

To ensure our deployment is successful, we have a few acceptance criteria to meet:

  • [ ] The frontend should build successfully in GitHub Actions.
  • [ ] Deployment should be triggered automatically on every push to the main branch.
  • [ ] The site should be accessible at https://carmandale.github.io/spy-fly/.
  • [ ] React Router navigation should work correctly, allowing users to navigate the app without issues.
  • [ ] All static assets (like images, CSS, and JavaScript files) should load properly with the correct paths.

Meeting these criteria means our deployment pipeline is working smoothly and our users can access and use our application without any hiccups.

Step-by-Step Guide to Deployment

Alright, let's dive into the step-by-step guide to deploying our React frontend to GitHub Pages using GitHub Actions. We’ll break it down into clear, actionable steps.

1. Create a GitHub Actions Workflow

First things first, we need to create a GitHub Actions workflow file. This file will define the steps GitHub Actions will take to build and deploy our frontend. Create a new file in your repository at .github/workflows/deploy.yml (or any name you prefer with the .yml extension). Here’s a sample workflow file:

name: Deploy to GitHub Pages

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'

      - name: Install dependencies
        run: cd frontend && npm install

      - name: Build
        run: cd frontend && npm run build

      - name: Deploy to GitHub Pages
        uses: JamesIves/github-pages-deploy-action@v4
        with:
          folder: frontend/dist # The folder where your build output is located

Let’s break down what this workflow does:

  • name: Deploy to GitHub Pages: This is the name of our workflow.
  • on: push: branches: - main: This specifies that the workflow will run whenever there's a push to the main branch.
  • jobs: deploy: This defines a job called deploy.
  • runs-on: ubuntu-latest: This specifies that the job will run on an Ubuntu virtual machine.
  • steps: This is a list of steps that will be executed.
    • actions/checkout@v3: This action checks out our code into the virtual machine.
    • actions/setup-node@v3: This action sets up Node.js with version 18.
    • npm install: This step installs the dependencies for our frontend.
    • npm run build: This step builds our frontend using the build script defined in our package.json file.
    • JamesIves/github-pages-deploy-action@v4: This action deploys our built frontend to GitHub Pages. The folder option specifies the directory containing our build output (in this case, frontend/dist).

This workflow automates the entire build and deployment process whenever you push changes to your main branch. It's the backbone of our continuous deployment pipeline.

2. Configure Frontend Build for GitHub Pages Deployment

Now, we need to configure our frontend build process to work correctly with GitHub Pages. Since GitHub Pages serves static files, we need to ensure our build output is optimized for this environment. This often involves setting the correct base URL and ensuring that all assets are served from the correct paths.

If you're using Vite, you can configure the base URL in your vite.config.js file. Here’s an example:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  base: '/spy-fly/', // Replace with your repository name
});

In this configuration, the base option specifies the base URL for our application. If your repository is named spy-fly, you should set base to /spy-fly/. This tells Vite to build the application with the correct paths for static assets. Setting the correct base URL is crucial for GitHub Pages to serve your application correctly. If this is misconfigured, your assets might not load, and your application might not function as expected.

3. Update React Router for GitHub Pages Compatibility

React Router is a fantastic library for handling client-side routing in React applications. However, it requires a bit of configuration to work seamlessly with GitHub Pages. The main issue is that GitHub Pages doesn't support the traditional routing mechanism used by React Router (i.e., using the BrowserRouter). Instead, we need to use HashRouter, which uses the hash portion of the URL (#) for routing.

To update your React Router configuration, you'll need to import HashRouter instead of BrowserRouter in your main application file (usually App.js or index.js). Here’s an example:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { HashRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <HashRouter>
      <App />
    </HashRouter>
  </React.StrictMode>
);

By using HashRouter, we ensure that React Router handles routing within the client-side application, and GitHub Pages can serve the correct content. This is a critical step for ensuring your application's navigation works on GitHub Pages.

4. Set Up Proper Base URL Configuration

We've already touched on setting the base URL in the Vite configuration, but it’s worth reiterating the importance of this step. The base URL tells your application where it's being served from. On GitHub Pages, this is typically /your-repository-name/. If you don't set the base URL correctly, your application might try to load assets from the root of the domain, which will result in 404 errors.

Make sure the base option in your vite.config.js file matches your repository name. If your repository is named spy-fly, your base should be /spy-fly/. Double-check this configuration to avoid common deployment issues.

5. Enable GitHub Pages in Repository Settings

The final step is to enable GitHub Pages in your repository settings. Go to your repository on GitHub, click on the