Continuous Integration Pipelines with GitHub Actions for (React) Developers (incl screencast)
Tags: react, javascript, github, devops
Published: 2022-03-19 12:18:12

---
title: Continuous Integration Pipelines with GitHub Actions for (React) Developers (incl screencast)
published: true
description: It’s easy to introduce bugs into production code. Professional teams use Continuous Integration pipelines to prevent this. Learn how to build your own with GitHub Actions.
tags: react, javascript, github, devops
canonical_url: https://profy.dev/article/continuous-integration-with-github-actions
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljrc5wr8l8zv2rf22rkt.png
 ---

If you don’t have experience working with a professional dev team yet, you probably don’t know how collaboration among developers typically works. One of the most important parts is the Git workflow. 

A very common workflow among professional teams is Trunk-Based Development. In a nutshell, it works like this:

1. You work on a separate Git branch and push it to GitHub.
2. You create a Pull Request where automated scripts check your code and your teammates review it.
3. You merge the Pull Request to the main branch once it’s approved.

We covered this workflow in detail in a [previous article](https://profy.dev/article/trunk-based-development-with-github). So if anything is unclear, I’d recommend reading it first (or have a look at [my free course where you can learn and practice this workflow](https://profy.dev/project/github-minesweeper)). 

On this page, we’ll focus on the automated scripts in the second step. This is called the Continuous Integration pipeline and typically runs tools like a linter (e.g. ESLint), code formatter (e.g. Prettier), or tests.

> If this is all sounds like Gibberish, no worries. Have a look at [my free course where you can learn and practice this workflow](https://profy.dev/project/github-minesweeper).
> 

In the video below I walk through the setup of a GitHub repository for a Next.js app that I created in a [previous blog post](https://profy.dev/article/setup-react-project). You can find a summary below the video. In a nutshell, you’ll learn

- How to set up a Continuous Integration pipeline with GitHub Actions to automatically run ESLint, Prettier, and tests in each Pull Request.
- How to prevent code from being merged to the main branch if it doesn’t pass the pipeline.
- How to use pre-commit hooks to run checks even before you can create a commit.

The application is part of the [upcoming React Job Simulator](https://profy.dev/waitlist) where you can work on an existing codebase using this and other professional workflows and tools. Just like you would in a real job.

{% embed https://www.youtube.com/watch?v=QH9rhtp_TMk %}

## Table of Contents

1. [Continuous Integration with GitHub Actions](#continuous-integration-with-github-actions)
2. [Status Checks: Prevent merges of Pull Requests that don’t pass the CI pipeline](#status-checks-prevent-merges-of-pull-requests-that-dont-pass-the-ci-pipeline)
3. [Pre-commit hooks: validate your code before a commit](#precommit-hooks-validate-your-code-before-a-commit)

## Continuous Integration with GitHub Actions

[In the previous article, we set up the GitHub repository to use branch protection](https://profy.dev/article/trunk-based-development-with-github#branch-protection-enforce-usage-of-pull-requests). This way we can enforce branches can only be merged to the main branch via a Pull Request that is approved by another teammate.

The approval process can be very valuable. But especially code reviews are also time-consuming. You don’t want to waste time complaining about details like code formatting. On top of that, it’s not feasible to test all the code by hand to ensure that the rest of the application still works as expected.

As you know, we have tools to assist us: TypeScript and ESLint to catch bugs, Prettier to format our code, and tests to make sure that our app works. 

With the help of a Continuous Integration pipeline, we can run all these tools within our Pull Requests. This way we decrease the effort spent on code reviews and reduce the risk of introducing bugs. And that again helps to merge Pull Requests frequently ([which is the whole meaning of Continuous Integration by the way](https://en.wikipedia.org/wiki/Continuous_integration)).

There are many tools to build CI pipelines. The simplest option for repositories on GitHub is probably GitHub Actions. It’s as easy as creating a file called  `.github/workflows/main.yml` in your repo. 

For my project, the file looks like this:

```yaml
name: CI

on:
  # runs on pushes to the main branch
  push:
    branches: [main]
  # also runs inside pull requests that target the main branch
  pull_request:
    branches: [main]

jobs:
  build:
    # uses a Ubuntu Docker image (like a virtual machine)
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: "14"
          cache: "npm"
      # install dependencies
      - run: npm ci
      # run ESLint & Prettier
      - run: npm run lint
      - run: npm run prettier
      # verify that there are no build errors
      - run: npm run build
      # run tests with Cypress
      - name: Cypress run
        uses: cypress-io/github-action@v2
        with:
          start: npm start
```

The following happens whenever a commit is pushed to the main branch or to a pull request that targets the main branch:

- A Ubuntu machine is spun up, the code from the repo checked out, and Node.js installed.
- ESLint and Prettier are run to check for bugs and correct code format.
- The project is built to verify that there are no TypeScript and build errors.
- The Cypress tests are run to verify that the app behaves as expected.

In our Pull Request, we now have status checks (one to be precise).

![Pull Request - CI status check](https://media.graphcms.com/2NjqqVu4SxW6ygqexTBD)

In case something goes wrong and the CI pipeline fails we can inspect the details. You just click on the “Details” link at the very right of the status check. 

Here is an example where I committed code that wasn’t formatted correctly. This looks just like the output of a normal terminal. 

![CI details](https://media.graphcms.com/b3TzQrUZRISR2VDvXgVX)

## Status Checks: Prevent merges of Pull Requests that don’t pass the CI pipeline

At this point, we force everyone on the team to use Pull Requests and we have a CI pipeline that automatically checks our code. Unfortunately, a developer can still decide to merge a PR even though it didn’t pass the CI pipeline. Wouldn’t it be awesome if we could prevent that?

That’s where our [branch protection rules from the previous article](https://profy.dev/article/trunk-based-development-with-github#branch-protection-enforce-usage-of-pull-requests) come in again. You can find an option “Require status checks to pass before merging” that we didn’t select before. Once our CI pipeline has run at least one time we can enable it and select the required CI jobs.

You simply edit the existing rules for the main branch, check the option, and select the job from the workflow file (in this case “build”).

![require status checks in branch protection rules](https://media.graphcms.com/B4Jgik3ShyhbButlhTq3)

Now the merge button inside a Pull Request is disabled whenever the CI pipeline fails.

![pull request - merge button disabled when ci fails](https://media.graphcms.com/dkS6Pil1QCYKeK76IiLA)

## Pre-commit hooks: validate your code before a commit

Once you start working with CI pipelines you realize that it takes a while to run them. It can be annoying to come back to a Pull Request after a few minutes only to realize that the CI failed because of a dumb ESLint error.

This is where pre-commit hooks come in handy. They allow you to automatically run scripts when you create a commit. If one of the scripts fails the commit is stopped. 

Since the goal is to commit frequently I wouldn’t recommend running complex tasks in pre-commit hooks. For example, running a whole test suite on every commit quickly gets annoying. Pre-commit hooks are best suited for fast scripts like `npm run lint` or `npm run prettier`. Especially when they only check the staged files and not the whole repository.

The easiest way to set up pre-commit hooks that only run on staged files is by using [lint-staged](https://github.com/okonet/lint-staged).

```yaml
npx mrm@2 lint-staged
```

This will install [Husky](https://github.com/typicode/husky) under the hood and set up some scripts to run before a commit. You can find them in the `lint-staged` section in your `package.json` file.

This is the `package.json` file for my project. I already adapted it to run on JavaScript and TypeScript files.

```yaml
{
  "scripts": { ... },
  "dependencies": { ... },
  "devDependencies": { ... },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": "eslint --cache --fix",
    "*.{js,jsx,ts,tsx,css,md}": "prettier --write"
  }
} 
```

When you try to commit code that contains an ESLint error the pre-commit hook will complain now.

![pre-commit hooks with husky prevent a commit](https://media.graphcms.com/g9SbtHdASPqy4ItwBmau)

Note that it’s easy to skip the pre-commit hooks by using the `git commit --no-verify` option. So you can compare our setup to form validation in web apps: 

- The pre-commit hooks are the validation on the frontend. They give quick feedback but you can easily hack them.
- The CI pipeline is the backend validation: It takes a bit longer to realize that something went wrong but you can’t simply work around them.

![Bootcamp for Self-Taught React devs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7ijm8eibvnde1i5d6b9.png)