⚡️ How to call an OAuth based API in React?
Tags: react, webdev, tutorial, pizzly
Published: 2020-09-02 15:43:19

---
title: ⚡️ How to call an OAuth based API in React?
published: true
description: It can be very tricky for React developers to request an OAuth based APIs. But it doesn't have to be so hard. Let's see how to make it great!
tags: react, webdev, tutorial, pizzly
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/mrw03h9cztrt6mtwfnic.jpg
---

Do you know what Facebook, Google, GitHub, and thousands more APIs have in common? They use OAuth to authenticate requests.

OAuth, especially OAuth 2.0, is now everywhere. It's a very powerful authentication framework that powers up developers to have granularity over the data that it needs.

# React + OAuth = 🤔

When it comes to OAuth-based API, your React app is not well-suited to send requests. You just can't hide your API keys deep into your codebase. Someone will easily find it.

What you need to do is to set up some backend service, that proxies requests to the third-party API. It can be fun to do, but it's a long process for a quick API call.

> For example, you will need a backend to protect your API keys. Declare routes, understand packages (_like Passport.js_), proxying requests, and dozens of more actions. It doesn't have to be so hard.

Today, I'll showcase an open-source project that I'm actively contributing to. It's called [Pizzly](https://github.com/Bearer/Pizzly) and it helps a lot with using API from a single page application.

Let's see how it looks like with a simple demo:
{% codesandbox rq78z view=preview %}

Curious about how you can do it on your application? Here's a full guide.

# The React skeleton 🦴

To learn how to make API calls to an API, we first need a React skeleton. And the least that we need is an app that consumes an API endpoint using OAuth2.

As you probably have a GitHub account, we will use that API, but you can easily switch to any other API that uses OAuth2 (Slack, Salesforce, ...) or OAuth1 (Twitter, Trello, ...).

Here's how the application will look like:

```jsx
import React, { useState } from 'react'
import Pizzly from 'pizzly-js'
import Profile from './Profile'

const App = () => {
  const [profile, setProfile] = useState()

  return (
    <div className="App">
      <h1>Hello!</h1>
      <p>
        Click the button bellow to retrieve your GitHub profile using{' '}
        <a target="_blank" rel="noopener noreferrer" href="https://github.com/Bearer/Pizzly">
          Pizzly
        </a>
        .
      </p>
      <button onClick={connect}>Retrieve your GitHub profile</button>
      {profile && <Profile profile={profile} />}
    </div>
  )
};

export default App;
```

It's a very basic React application that renders the user's profile as a plain JSON when it has been fetched. Otherwise, it asks the user to connect to GitHub.

# The authentication 🔐

Here, we gonna use [Pizzly](https://github.com/Bearer/Pizzly), the open-source project I told you about a few lines above. 

It provides a `.connect()` method that triggers an authentication flow from your frontend, which you can handle with callbacks. No need to create a redirect URL, deal with backend, etc.

Let's see how to update the skeleton above to use with Pizzly.

First, we need to initialize Pizzly:

```jsx
// Initialize Pizzly
const pizzly = new Pizzly({
  host: PIZZLY_HOSTNAME,
  publishableKey: PIZZLY_PUBLISHABLE_KEY
})

const github = pizzly.integration('github', {
  setupId: PIZZLY_SETUP_ID_GITHUB_DEMO_APP
})
```

Then, we add a new `connect()` method to trigger the authentication flow:

```jsx
const App = () => {

  // ...

  /**
   * The connect method lets us authenticate a user
   * to our GitHub application (i.e. the OAuth dance)
   */

  const connect = () => {
    github
      .connect()
      .then(({ authId }) => {
        console.log('Sucessfully connected!', authId)
        fetchProfile(authId)
      })
      .catch(console.error)
  }

  // ...
};

export default App;
```

That's it. A few lines of code in your application and you are ready to handle any OAuth based API 💪.

# The configuration 🤖

Pizzly is a self-hosted OAuth manager. This means that you need to host it somewhere, for example on Heroku (it takes 30 seconds). Once hosted, you can access Pizzly's dashboard, which is where you configure your GitHub integration.

![Pizzly dashboard](https://raw.githubusercontent.com/Bearer/Pizzly/master/views/assets/img/docs/pizzly-dashboard-all-apis.png)

To deploy your own Pizzly instance right now, click on any of the following button:

| Heroku                                                                                                                                                                                                                  | Platform.sh                                                                                                                                                                                                                                                                                                                                                                         |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <a href="https://heroku.com/deploy?template=https://github.com/Bearer/Pizzly" rel="nofollow" target="_blank"><img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy to Heroku" width="184" height="40"></a> | <a href="https://console.platform.sh/projects/create-project/?template=https://github.com/Bearer/Pizzly&utm_campaign=deploy_on_platform?utm_medium=button&utm_source=affiliate_links&utm_content=https://github.com/Bearer/Pizzly" rel="nofollow"><img src="https://platform.sh/images/deploy/deploy-button-lg-blue.svg" alt="Deploy with Platform.sh" width="180" height="40"></a> |

Then, select the GitHub API. And configure it by saving your application's client ID, client credentials and scopes. You will get them from GitHub by following [this guide](https://docs.github.com/en/developers/apps/creating-an-oauth-app).

Once your Pizzly instance is created and you have configured a GitHub application, edit your React application with the following values:

```js
// Pizzly environment variables, make sure to replace
// these with those of your own Pizzly instance
const PIZZLY_HOSTNAME = "";
const PIZZLY_PUBLISHABLE_KEY = "";
const PIZZLY_SETUP_ID_GITHUB_DEMO_APP = "";
```

The least that you need is `PIZZLY_HOSTNAME`. The two others are optional.

# An authenticated API request 🎉

Alright, we have already spend a few minutes on the configuration. Let's move back to funny things.

The [GitHub API provides a handy endpoint (`/user`)](https://docs.github.com/en/rest/reference/users#get-the-authenticated-user) to retrieve the profile of the authenticated user. This endpoint uses OAuth authentication, so it looks like a good use case.

Let's add a new method to our application to do that:

```jsx
const App = () => {
  // ...

  /**
   * The fetchProfile method retrieves the authenticated
   * user profile on GitHub (the request is proxied through Pizzly)
   */

  const fetchProfile = async (authId) => {
    await github
      .auth(authId)
      .get("/user")
      .then((response) => response.json())
      .then((json) => setProfile(json));
  };

  // ...
};

export default App;
```

And _voilà_!

> _NB: To authenticate the request, we have provided an `authId`. It's like a user identity for that particular API. It was generated (and saved) with the `connect()` method._

# What's next? 💡

You now know how to authenticate a user towards any OAuth based API using React. If you prefer Vue.js, [the same tutorial is available for Vue.js](https://dev.to/bearer/how-to-use-an-oauth-based-api-in-vue-js-1elo).

It's easily adaptable to [all the most famous APIs](https://github.com/Bearer/Pizzly/wiki/Supported-APIs). No need to create backend routes or understand every single concept of OAuth. Pizzly takes care of that for you (and for the experts, Pizzly automatically refreshes the `access_token`).

Again, [have a look at the CodeSandbox](https://codesandbox.io/s/pizzly-github-react-demo-rq78z) to have a full understanding of the code and share your thoughts/questions in the comments below.

And if you've liked this tutorial, please add a star to Pizzly on GitHub. Here's the link: [https://github.com/Bearer/Pizzly](https://github.com/Bearer/Pizzly).