Introduction
In this tutorial, we'll show you how to add authentication to your React SPA with any provider of your choice using Kobble.
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:
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 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
- Create a new Project
- Go to 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.
Select your authentication providers
Kobble has already created a customer portal for us. But now, we need to activate the authentication providers we want.
- Go to Authentication and activate the providers of your choice (it's straightforward, but you can read the docs if needed).
- That's it.
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 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:
npm i -S @kobbleio/auth-spa-js
Then, create a file to init the SDK:
// 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.
Implement the login
The OAuth flow will work as follows:
- the user clicks on the login button
- he's redirected to your Kobble customer portal
- 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:
// 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.
// 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:
/**
* 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.
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 :)
Top comments (0)