> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kobble.io/llms.txt
> Use this file to discover all available pages before exploring further.

# React quickstart

> Add authentication to your React application in under 10 minutes using Kobble SDK.

## You will learn how to:

* Create a new React application using Vite
* Configure `@kobbleio/react` SDK
* Protect your application routes

<Note>Pre-requisites: You need to [set up your Kobble account](/learning/quickstart/setup) before starting this guide.</Note>

## Example repository

[<img src="https://mintcdn.com/kobble/hy82n-p3NucxH50S/images/react-auth-example-banner.png?fit=max&auto=format&n=hy82n-p3NucxH50S&q=85&s=012c8d36440b6e61ca295fccf771ac85" alt="React Auth Example" width="1792" height="321" data-path="images/react-auth-example-banner.png" />](https://github.com/kobble-io/react-auth-example)

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](https://www.npmjs.com/package/@kobbleio/react) SDK to manage the authentication state of the application.

Check our the repository for more information:

* [**Repository**](https://github.com/kobble-io/react-auth-example)
* [**Demo**](https://kobble-react-auth-example.vercel.app)

## Getting started

<Note>
  This guide uses our @kobbleio/react SDK. To use a lower-level SDK such as @kobbleio/javascript, check our [React SPA quickstart guide](/learning/quickstart/react-javascript).
</Note>

<Steps>
  <Step title="Create your React application">
    Scaffold your new React application using [Vite](https://vitejs.dev/guide/).

    <CodeGroup>
      ```bash npm theme={null}
      npm create vite@latest my-react-app -- --template react-ts
      cd my-react-app
      npm install
      npm run dev
      ```

      ```bash yarn theme={null}
      yarn create vite@latest my-react-app -- --template react-ts
      cd my-react-app
      yarn install
      yarn run dev
      ```

      ```bash npm theme={null}
      pnpm create vite@latest my-react-app -- --template react-ts
      cd my-react-app
      pnpm install
      pnpm run dev
      ```
    </CodeGroup>
  </Step>

  <Step title="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.

    <CodeGroup>
      ```bash npm theme={null}
      npm install @kobbleio/react
      ```

      ```bash yarn theme={null}
      yarn add @kobbleio/react
      ```

      ```bash pnpm theme={null}
      pnpm add @kobbleio/react
      ```
    </CodeGroup>
  </Step>

  <Step title="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:

    ```tsx theme={null}
     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>
     );
    ```
  </Step>

  <Step title="Setup the environment variables">
    Create a `.env` file at the root of your project and add the following environment variables.

    ```env theme={null}
    VITE_KOBBLE_DOMAIN=https://your-project.portal.kobble.io
    VITE_KOBBLE_CLIENT_ID=your-client-id
    VITE_KOBBLE_REDIRECT_URI=http://localhost:3000/callback
    ```

    <Note>**KOBBLE\_DOMAIN** and **KOBBLE\_CLIENT\_ID** can be found in [the Kobble Application we created earlier](/learning/quickstart/setup). The **REDIRECT\_URI** must match the callback route we're going to configure in the next step of this tutorial.</Note>
  </Step>

  <Step title="Create a callback handler">
    Install and configure [React Router](https://reactrouter.com/en/main/start/overview).

    <Note>If you're not familiar with React Router, you can check our router configuration [here](https://github.com/kobble-io/react-auth-example/blob/main/src/router.tsx).</Note>

    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.

    ```tsx theme={null}
    // 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;
    ```
  </Step>

  <Step title="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.

    ```tsx theme={null}
    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>
        )
    }
    ```
  </Step>

  <Step title="Login and Logout components">
    To trigger a login or logout flow, you can simply use our `<LoginButton />` and `<LogoutButton />` components.

    ```tsx theme={null}
    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.

    ```tsx theme={null}
    <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.
  </Step>

  <Step title="Going further">
    At this stage, you have successfully added authentication to your React application using **[Kobble](https://kobble.io)** 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:

    ```typescript theme={null}
    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:

    ```typescript theme={null}
    import { useAuthStateChanged } from '@kobbleio/react';

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

#### 🎉 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](https://github.com/kobble-io/react-auth-example).
