Authenticate users in your React SPA with Kobble
Tags: react, tutorial, authentication, kobble
Published: 2024-04-08 08:09:10

## Introduction

In this tutorial, we'll show you how to add authentication to your React SPA with any provider of your choice using [Kobble](https://kobble.io).

It's so simple that it won't take more than 10 minutes to get setup.

## Demo

Here's a demo of what we're going to build:

[Demo Page](https://kobble-react-auth-example.vercel.app)


![Screenshot example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9lowd1tdtscqrpq3lb1p.png)

Here are the features available in this basic single page app:

- Users can sign un and sign in
- We can view their profile information
- Get an access token
- Get an id token and more.

Almost everything is handled by Kobble, so you don't have to bother with authentication details.

## What's Kobble?

[Kobble.io](https://kobble.io) is a monetization platform as a service. It provides a customer portal as a service with built-in Authentication, price tables, quota management and more.

Here we're going to use their authentication system but you will be able to go further later!

## Create an application on Kobble

Let's get into it!

- Sign in for free at [Kobble](https://kobble.io)
- Create a new Project
- Go to [Applications](https://app.kobble.io/p/applications) and create an application
- In the Redirect URI section, add **http://localhost:3000/callback** 

> The callback URL must match your React app. We'll create that callback page later on.

![Creating a Kobble Application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tz7t9kkjdu1xa978rsfz.png)


## Select your authentication providers

[Kobble](https://kobble.io) has already created a customer portal for us. But now, we need to activate the authentication providers we want.

- Go to [Authentication](https://app.kobble.io/p/authentication) and activate the providers of your choice (it's straightforward, but you can read [the docs](https://docs.kobble.io/product/authentication/overview) if needed).
- That's it.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gbajw4r0osefjhvk0vh.png)


Your Customer Portal should be up and running already at **https://[your-project].portal.kobble.io** and you can customize it on the [Customer Portal](https://app.kobble.io/p/portal/branding) section of your dashboard.


## Setting up your React app

Here I'm assuming you already have a React app up and running.

If you don't, maybe it's worth starting with the full code we provide at the end of this tutorial. 

### Install Kobble SDK

In your terminal, run the following command:

```bash
npm i -S @kobbleio/auth-spa-js
```

Then, create a file to init the SDK:

```typescript
// src/kobble/index.ts

import { createKobbleClient } from '@kobbleio/auth-spa-js'

export const kobbleClient = createKobbleClient({
  domain: import.meta.env.VITE_KOBBLE_DOMAIN,
  clientId: import.meta.env.VITE_KOBBLE_CLIENT_ID,
  redirectUri: import.meta.env.VITE_KOBBLE_REDIRECT_URI
})
```

Replace the environment variables with the values provided in the Kobble Application we created earlier.

![Kobble Application Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/be30lgejsvy05rf66g5e.png)


### Implement the login

The OAuth flow will work as follows:

1. the user clicks on the login button
2. he's redirected to your Kobble customer portal
3. once logged in, he's redirected back to your callback URL to complete the OAuth flow

Kobble provides everything we need to handle this.

#### Handle login

To handle login, you only have to use the `loginWithRedirect()` method provided by our Kobble instance.

You just have to create a button anywhere on your app that looks like this:

```react
// import our kobble instance
import { kobbleClient } from "../kobble";

// ...
// define our login handler
const login = () => {
    kobbleClient.loginWithRedirect();
};

// ...
// rendering the button

<button onClick={login}>Login</button>
```

#### Handle the callback

To make sure our flow can be completed, let's create a callback page and use the **handleRedirectCallback()** method when it's first loaded.


```react
// Inside your Callback page component

    const navigate = useNavigate();

    useEffect(() => {
        const authenticate = async () => {
            try {
                await kobbleClient.handleRedirectCallback();
                navigate('/', {
                    replace: true,
                });
            } catch (e: any) {
                console.log(e.message);
                setError(e.message);
            }
        };

        authenticate();
    }, [navigate]);

// Rest of your code...
```

> Make sure your callback page URL matches the Redirect URI you previously used.


#### Listen to the user state changes

That's it. Your React app is ready to authenticate your users.

Now, you can listen to the user's state using the following method:

```typescript
/**
 * This callback is triggered every time the user object changes:
 * - on login
 * - on logout
 * - on access token refreshed
 */
kobbleClient.onAuthStateChanged((data) => {
  console.log('User', data.user)
})

```

#### Other methods

The Kobble client also exposes a lot of utility functions, such as:

- logout()
- getUser()
- getIdToken()
- getAccessToken()

These functions are especially useful to validate the user is authenticated when dealing with your backend.

## Conclusion

In under 10 minutes, we added authentication to our React application using [Kobble.io](https://kobble.io).


**Demo website:**

https://kobble-react-auth-example.vercel.app

**Full Code**:

https://github.com/kobble-io/react-auth-example


## Thank you!
If you liked this tutorial, feel free to smash the like button and react in the comments below :)