You will learn how to:

  • Create a new React application using Vite
  • Configure @kobbleio/react SDK
  • Protect your application routes
Pre-requisites: You need to set up your Kobble account before starting this guide.

Example repository

This is a simple React starter project that demonstrates how to implement authentication in a React application.

It uses react-router, pinia, tailwind and @kobbleio/react SDK to manage the authentication state of the application.

Check our the repository for more information:

Getting started

This guide uses our @kobbleio/react SDK. To use a lower-level SDK such as @kobbleio/javascript, check our React SPA quickstart guide.

1

Create your React application

Scaffold your new React application using Vite.

2

Install @kobbleio/react

Our auth SDK for React helps you to easily authenticate your users in your React application and manage their session. It also provides a set of methods, hooks and components to help you protect your routes and manage the user state.

3

Use the KobbleProvider

To use the SDK, you must wrap your App component with the KobbleProvider component.

Here’s an example that also uses React Router:

 import ReactDOM from 'react-dom/client';
 import './index.css';
 import { router } from "./router";
 import { RouterProvider } from "react-router-dom";
 import { KobbleProvider } from "@kobbleio/react";

 const root = ReactDOM.createRoot(
 document.getElementById('root') as HTMLElement
 )

 root.render(
 <KobbleProvider domain={import.meta.env.VITE_KOBBLE_DOMAIN}
                 clientId={import.meta.env.VITE_KOBBLE_CLIENT_ID}
                 redirectUri={import.meta.env.VITE_KOBBLE_REDIRECT_URI}>
     <RouterProvider router={router} />
 </KobbleProvider>
 );
4

Setup the environment variables

Create a .env file at the root of your project and add the following environment variables.

VITE_KOBBLE_DOMAIN=https://your-project.portal.kobble.io
VITE_KOBBLE_CLIENT_ID=your-client-id
VITE_KOBBLE_REDIRECT_URI=http://localhost:3000/callback
KOBBLE_DOMAIN and KOBBLE_CLIENT_ID can be found in the Kobble Application we created earlier. The REDIRECT_URI must match the callback route we’re going to configure in the next step of this tutorial.
5

Create a callback handler

Install and configure React Router.

If you’re not familiar with React Router, you can check our router configuration here.

Then create a new page view to handle our callback src/pages/Callback.tsx.

Use the <HandleCallback /> component to handle the callback and redirect the user to the home page automatically.

// src/pages/Callback.tsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { HandleCallback } from "@kobbleio/react";

const Callback: React.FC = () => {
    const [error, setError] = useState<string | null>(null);
    const navigate = useNavigate();

    return (
        <HandleCallback navigate={navigate} afterSignInUrl={'/'} onError={(message) => setError(message)}>
            {error && <span>An error occurred: {error}</span>
        </HandleCallback>
    );
};

export default Callback;
6

Handling user state

The SDK exposes multiple hooks and components to handle authentication.

You can use the useAuth hook to get the user state and the LoginButton component to trigger the login process.

First, we can use the <SignedIn /> and <SignedOut /> components to show different content based on the user’s authentication state.

import { SignedIn, SignedOut, useAuth } from '@kobbleio/react';

const MyPage: React.FC = () => {
    const { user } = useAuth();

    return (
        <div>
            <SignedIn>
                <p>Welcome, {user.name}</p>
            </SignedIn>

            <SignedOut>
                <p>You must login</p>
            </SignedOut>
        </div>
    )
}
7

Login and Logout components

To trigger a login or logout flow, you can simply use our <LoginButton /> and <LogoutButton /> components.

import { SignedIn, SignedOut, useAuth, LoginButton, LogoutButton } from '@kobbleio/react';

const MyPage: React.FC = () => {
    const { user } = useAuth();

    return (
        <div>
            <SignedIn>
                    <p>Welcome, {user.name}</p>
                    <LogoutButton />
            </SignedIn>

            <SignedOut>
                <p>You must login</p>
                <LoginButton />
            </SignedOut>
        </div>
    )
}

There’s no need to pass any handlers to these components, they will handle everything for you.

Customize your buttons:

By default, these buttons will render as simple buttons. You can customize them by passing a child prop.

<LoginButton>
    <button className="rounded-full border border-[#236456] bg-[#112220] text-[#33C6AB] py-1 px-3">
        Login
    </button>
</LoginButton>

Again, no need to pass any handler to the button, it will handle everything for you.

8

Going further

At this stage, you have successfully added authentication to your React application using Kobble SDK.

Now you can use all methods provided by the Kobble Provider to protect your routes, get the user profile, listen to the user state changes and more.

Here are some useful examples:

const { kobble } = useKobble();
const { user, isAuthenticated } = useAuth();

// In an async function
const user = await kobble.getUser()

const accessToken = await kobble.getAccessToken()

const idToken = await kobble.getIdToken()

const supabaseToken = await kobble.getSupabaseToken()

await kobble.loginWithRedirect()

await kobble.logout

You can also listen to the user state changes:

import { useAuthStateChanged } from '@kobbleio/react';

useAuthStateChanged((data) => {
    // Handle user state change as needed
    console.log(data.user) // null | User
})

🎉 You made it!

You have successfully added authentication to your React application using Kobble SDK.

You can find a complete example of this tutorial in the React Auth Example repository.