DEV Community

Cover image for ⚡️ How to call an OAuth based API in React?
Corentin for Mailmeteor

Posted on • Edited on

⚡️ How to call an OAuth based API in React?

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 and it helps a lot with using API from a single page application.

Let's see how it looks like with a simple demo:

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:

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;
Enter fullscreen mode Exit fullscreen mode

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, 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:

// 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
})
Enter fullscreen mode Exit fullscreen mode

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

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;
Enter fullscreen mode Exit fullscreen mode

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

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

Heroku Platform.sh
Deploy to Heroku Deploy with Platform.sh

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.

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

// 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 = "";
Enter fullscreen mode Exit fullscreen mode

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) 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:

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;
Enter fullscreen mode Exit fullscreen mode

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.

It's easily adaptable to all the most famous 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 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.

Top comments (1)

Collapse
 
camilahill profile image
CamilaHill

How do you use OAuth in React?
Surah to get love back