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
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.
Create your React application
Scaffold your new React application using Vite.
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.
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:
Setup the environment variables
Create a .env
file at the root of your project and add the following environment variables.
Create a callback handler
Install and configure React Router.
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.
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.
Login and Logout components
To trigger a login or logout flow, you can simply use our <LoginButton />
and <LogoutButton />
components.
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.
Again, no need to pass any handler to the button, it will handle everything for you.
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:
You can also listen to the user state changes:
🎉 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.