Geshan Manandhar Geshan is a seasoned software engineer with more than a decade of software engineering experience. He has a keen interest in REST architecture, microservices, and cloud computing. He also blogs at geshan.com.np.

Cloudflare Pages tutorial: Deploying a React app via GitHub

5 min read 1619

Introduction

React is an ultra-popular frontend library for building user interfaces. As the output is HTML, CSS, and JavaScript, it can be hosted on multiple services like Github pages or Netlify, to name a few.

Recently, Cloudflare Pages has become generally available, which makes it another great service on which to host your React app. Cloudflare Pages is secure, fast, and highly scalable.

In this step-by-step tutorial, we will host a demo React app setup on Cloudflare Pages. Let’s get going.

Why Cloudflare Pages?

Of course, React (or any other static output) can be hosted on at least half a dozen services for free. Why should we go for Cloudflare Pages?

In addition to the regular features like preview deployments and Github integration, Cloudflare Pages has custom domains, redirects, and unlimited bandwidth, all for free. All of these features at zero dollars a month, and we get a fast network, security with free SSL, and amazing scalability.

Screenshot of Cloudflare Pages homepage

Prerequisites

Before we jump into the code below, here are some prerequisites:

    1. Previous knowledge of JavaScript and React
    2. Previous knowledge of npm and npx
    3. Node.js and npm/yarn working on your environment of choice
    4. Previous knowledge of Git, and a working Github account
    5. A Cloudflare account, for which you can sign up for free

Time to get cracking.

Set up a React app with Create React App

As the first step of this guide, we will set up React with Create React App (CRA). If you don’t have CRA installed you can do so with npm install -g create-react-app. To initiate a React app boilerplate with CRA we will execute the following command:

bash
npx create-react-app react-cloudflare-pages

This will set up the whole React boilerplate for us. As soon as it runs, we will see an output like the one below:

We made a custom demo for .
No really. Click here to check it out.

Screenshot of development environment after installing Create React App

It will take a couple of minutes to download and set up the React boilerplate and finish up with the output as follows:

Screenshot of Create React App output after install

As instructed in the image above, to check if our React app is working we can run:

bash
cd react-cloudflare-pages
yarn start

It will run the development server, and you can runhttps://localhost:3000 in your default browser to show an output like so:

Default Create React App screen

Congrats! Our React boilerplate with CRA is working.

Next up, we will push this basic code to Github and later change it to get a list of users from a mock API, and show some of its fields.

Push the boilerplate code to Github

To push our basic React boilerplate, we will create a new Github repository as follows:

Screenshot of Github's Create New Repository menu

It is ok to keep it public and empty. Scroll to the bottom of the page and click the Create Repository button. We will see a page similar to the below:

Screenshot of Github page after new repository is created

Next, copy the SSH URL to the Github repository, which in my case was [email protected]:geshan/react-cloudflare-pages.git, and add it as a remote running the following command in our project root to push the code:

bash
git remote add origin [email protected]:geshan/react-cloudflare-pages.git
git push origin master

It will look something like the following:

Screenshot of code being pushed to Github

Consequently, we will update the code to call the mock API and list some of the user details. If you want, you can create a new Git branch to do the following changes, but I will leave that up to you.

Update the boilerplate to call a mock API

Our React boilerplate is up and running, and it has been pushed to GitHub too. Now, we will change the code to call a mock list of 10 users and show some fields in our React app.

To do this we will change the src/App.js to look like this below:

js
import {Component} from 'react';
import Users from './components/users';

class App extends Component {
  state = {
    users: []
  };

  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then((data) => {
        this.setState({ users: data })
      })
      .catch(console.log)
  }

  render() {
    return (
      <Users users={this.state.users} />
    )
  }
}

export default App;

Note that we have removed the unnecessary CSS file and logo.

Time to dive a bit deeper into what the code is doing. First, we are importing Component from React, then importing another component called users, which we will write next.

Then in the App class that extends the React component, we are introducing a state with the users array. When the component mounts, we fetch a list of 10 users from our mock API – http://jsonplaceholder.typicode.com/users – and set it in the users of the state. In case of an error, we log it.

For the final step in the main App component, we render the Users component which we will write up next.

As we use the users component above, we will create a new file src/components/users.js that will contain the following:

js
const Users = ({ users }) => {
  return (
    <div className="users">
      <center><h1>Application Users</h1></center>
      {Array.isArray(users) && users.map((user) => (
        <div className="user" key={user.id}>
          <div className="user-details">
            <h2 className="user-name">{user.name}</h2>
            <h3 className="user-email">{user.email}</h3>
            <h4 className="user-company">Company: {user.company.name}</h4>
            <hr/>
          </div>
        </div>
      ))}
    </div>
  )
};

export default Users

Let’s look at how this file works. It is a very simple component that relies on the users being passed in as an array. We check if it is an array and loop through the users. Then we print out the user’s name, email, and user’s company name.

If we want, we can delete the unnecessary files after this change with the following command:

bash
rm -rf src/App.css src/logo.svg src/App.test.js

After that we can run yarn start and see the following output:

Screenshot of application users with name, email, and company name

Hurray! The mock API is being called properly and we see the user’s name, email, and company name rendering correctly. After this, we will push our code change to GitHub and wire it up with Cloudflare Pages. If you want to look at what files have changed you can have a look at this pull request.

Push the app to Github

To push our changes to the master branch we will run the following commands on the project root:

bash
git add .
git add -u #because we have deleted files
git commit -m "Call the mock users API"
git push origin master # if you are in a different branch push that and open a PR

After the push, you should see the changes reflected in your Github repository as well. Now it’s time to get a Cloudflare Pages URL for our React app.

Log in to Cloudflare Pages

To connect your React app with Cloudflare pages, create a Cloudflare account if you haven’t done so already. Then, log in to Cloudflare and click Pages on the right:

Screenshot of Google Cloudflare home page

We will see a page similar to below:

Screenshot of cloudflare pages connect github tab

Click on Connect Github account. We will be redirected to Github where we can configure the accounts and repositories we want CloudFlare to access:

Screenshot of Github install cloudflare pages tab

Click on the account into which you pushed the above React app (it will probably be your personal account) and choose the right repository to connect to:

Screenshot of Github install and authorize Cloudflare pages tab

It is better to give access to the required repository only. After giving access we will be redirected to Cloudflare Pages where were can deploy the React app, select the repository, and click Begin Setup as below:

Screenshot of Cloudflare Pages after successful link to Github repository

Next, we will configure the main branch as master:

Screenshot of Cloudflare pages set up builds and deployments tab

Scroll below on that page to configure the build settings as follows:

Screenshot of cloudflare pages build settings tab

I had to update npm build with yarn build in the build command field because CRA uses yarn in place of npm.

Then click Save and Deploy. If all goes well, the project will be created and start to deploy as seen below:

Screenshot of Cloudflare Pages with Github repo under Pages section

After a couple of minutes, the build should be done, and if we click the title of the project react-cloudflare-pages we will see a page like below:

Screenshot of github repo successfully deployed in Cloudflare pages

If we click the link below Deployment, which is a pages.dev URL, we should be able to see our React app deployed on Cloudflare Pages as follows:

Screenshot of application users app deployed via Cloudflare pages

As seen above, it is an HTTPS Cloudflare Pages URL on pages.dev.

Preview deployment in action

For us to see how previewing deployment works, I am going to change the Company label to Company Name on line 10 of src/components/users.js.

We will push it in a branch called preview-deployment, which will give us a preview on Github when we open a pull request. After it is built successfully on Cloudflare Pages, it will give us a unique link to the changes as a comment, which can be seen here:

Screenshot of Github repo with comment by Cloudflare pages stating successful deployment

This is a very neat feature to see the changes on a fully functioning URL.

Next steps

We can easily configure a custom domain for our React app on Cloudflare Pages, which is free as well. In addition, redirects and access control for the preview deployments can also be configured. I will leave it up to you to explore them.

Conclusion

As we have seen in this step-by-step tutorial, Cloudflare Pages is easy to set up for your React app or any other frontend framework. There is no need to configure a build process on something like Github actions or another CI system.

Connect your Github repo with Cloudflare Pages, and use the build command once as each pull request automatically gets a preview deployment URL. Exploit the power of Cloudflare Pages for free and make your websites fly.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Geshan Manandhar Geshan is a seasoned software engineer with more than a decade of software engineering experience. He has a keen interest in REST architecture, microservices, and cloud computing. He also blogs at geshan.com.np.

Testing accessibility with Storybook

One big challenge when building a component library is prioritizing accessibility. Accessibility is usually seen as one of those “nice-to-have” features, and unfortunately, we’re...
Laura Carballo
4 min read

Leave a Reply