React Client Installation
The Authava React client provides a simple way to add authentication to your React applications. It includes pre-built components, hooks, and utilities to handle the authentication flow.
Installation
Install the Authava React client using npm or yarn:
# Using npm
npm install @authava/react
# Using yarn
yarn add @authava/react
Basic Setup
1. Configure the AuthavaProvider
Wrap your application with the AuthavaProvider
component to provide authentication context:
// src/index.jsx or src/App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { AuthavaProvider } from '@authava/react';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<AuthavaProvider
domain="auth.yourdomain.com"
>
<App />
</AuthavaProvider>
</React.StrictMode>,
document.getElementById('root')
);
2. Add Login and Logout Functionality
Use the useAuthava
hook to access authentication functions and state:
// src/components/LoginButton.jsx
import React from 'react';
import { useAuthava } from '@authava/react';
export const LoginButton = () => {
const { login, isAuthenticated, logout, user } = useAuthava();
if (isAuthenticated) {
return (
<div>
<p>Hello, {user.name}!</p>
<button onClick={() => logout()}>Log Out</button>
</div>
);
}
return <button onClick={() => login()}>Log In</button>;
};
3. Protect Routes
Use the ProtectedRoute
component to restrict access to authenticated users:
// src/components/PrivateRoute.jsx
import React from 'react';
import { Route } from 'react-router-dom';
import { ProtectedRoute } from '@authava/react';
export const PrivateRoute = ({ component, ...args }) => (
<ProtectedRoute component={component} {...args} />
);
// Usage in your router
<PrivateRoute path="/profile" component={Profile} />
Configuration Options
The AuthavaProvider
component accepts the following props:
Prop | Type | Description |
---|---|---|
domain | string | Required. Your Authava authentication domain (e.g., auth.yourdomain.com ) |
clientId | string | Required. Your client ID from the Authava dashboard |
redirectUri | string | Required. The URL to redirect to after authentication |
audience | string | Optional. The API audience for access tokens |
scope | string | Optional. The scopes to request (default: openid profile email ) |
onRedirectCallback | function | Optional. Function to call after authentication redirect |
cacheLocation | string | Optional. Where to store tokens ('memory' or 'localStorage' , default: 'localStorage' ) |
useRefreshTokens | boolean | Optional. Whether to use refresh tokens (default: false ) |
Advanced Usage
Custom Authentication Flow
You can customize the authentication flow using the useAuthava
hook:
import { useAuthava } from '@authava/react';
const { login } = useAuthava();
// Custom login with specific parameters
const handleCustomLogin = () => {
login({
redirectUri: 'https://app.yourdomain.com/callback',
scope: 'openid profile email read:data',
prompt: 'login',
});
};
Accessing Tokens
Access the authentication tokens using the getTokenSilently
function:
import { useAuthava } from '@authava/react';
const { getTokenSilently } = useAuthava();
const callApi = async () => {
try {
const token = await getTokenSilently();
const response = await fetch('https://api.yourdomain.com/data', {
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error calling API:', error);
}
};
Handling Authentication Events
Listen for authentication events using the useAuthavaEvents
hook:
import { useEffect } from 'react';
import { useAuthavaEvents } from '@authava/react';
const AuthEvents = () => {
const { addListener, removeListener } = useAuthavaEvents();
useEffect(() => {
const handleLogin = (user) => {
console.log('User logged in:', user);
// Analytics tracking, etc.
};
const handleLogout = () => {
console.log('User logged out');
// Clear user data, etc.
};
addListener('login', handleLogin);
addListener('logout', handleLogout);
return () => {
removeListener('login', handleLogin);
removeListener('logout', handleLogout);
};
}, [addListener, removeListener]);
return null;
};
Next Steps
- Explore the React client on GitHub
- Integrate authentication into your React application
- Customize the authentication experience