React SDK
The Kinde React SDK allows developers to quickly and securely integrate a new or existing React application to the Kinde platform.
This new SDK (v5) is optimized to work with React version 18+.
If you are currently using v4, refer to this migration information to update to v5.
New to Kinde? Kinde is the all-in-one developer platform for authentication, access management and billing - secure and monetize your SaaS from day one. Get started for free (no credit card required).
What you need
Link to this sectionSet up a Kinde application
Link to this section- Sign in to your Kinde dashboard and select Add application
- Enter a name for the application (e.g., “My React App”)
- Select Front-end and mobile as the application type, then select Save.
- On the Quick start page, select React from the list of Front-end SDKs, then select Save.
Using non-production environments
Link to this sectionKinde allows you to have one production environment and multiple non-production environments. If you would like to use different environments as part of your development process, learn more about environments here.
Option 1: Install the Starter kit
Link to this section-
On the Quick start page, select Set for both callback URL and logout URL. This will set
http://localhost:3000as your default URLs. If you want to use a different URL, you can change it in the Details page. -
Download the React starter kit
-
Go to the root of your project and install the dependencies:
Terminal window cd react-starter-kitnpm install -
Create an environment variable file:
Terminal window cp .env_sample .env -
Copy the environment variables from the Quick start page to the
.envfile and save changes. -
Start the development server:
Terminal window npm run dev -
Open the browser and navigate to http://localhost:3000 to see the application.
-
Sign up for a new user.
-
Go to your Kinde dashboard > Users to find your newly created user.
Option 2: Install for an existing project
Link to this section-
On the Quick start page, select Existing codebase and edit your project URL (defaults to
http://localhost:3000) -
Select Set for both callback URL and logout URL.
-
Open your project in your terminal and install the Kinde dependency with the following command:
Terminal window npm i @kinde-oss/kinde-auth-reactTerminal window yarn add @kinde-oss/kinde-auth-reactTerminal window pnpm add @kinde-oss/kinde-auth-react -
Import the
KindeProvidercomponent and wrap your application in it.app.jsx import { KindeProvider } from '@kinde-oss/kinde-auth-react';const App = () => (<KindeProviderclientId="<your_kinde_client_id>"domain="<your_kinde_domain>"logoutUri={window.location.origin}redirectUri={window.location.origin}><Routes /></KindeProvider>);Kinde uses a React Context Provider to maintain its internal state in your application.
Replace the
<your_kinde_client_id>and<your_kinde_domain>placeholders in the code block above with the values from the Details > App keys section.
Now that you have set up your Kinde React application, check out the rest of the documentation to configure your app.
Authentication
Link to this sectionSign-in and sign-up
Link to this sectionLink components:
The Kinde React SDK ships with standard components for Login and Register:
import { LoginLink, RegisterLink } from '@kinde-oss/kinde-auth-react/components';
{/* somewhere in your component */}<LoginLink>Sign in</LoginLink><RegisterLink>Sign up</RegisterLink>Hook methods:
Kinde also comes with a useKindeAuth hook with the methods login and register to start the flow.
import { useKindeAuth } from '@kinde-oss/kinde-auth-react';
{/* within your component */}const { login, register } = useKindeAuth();
<button onClick={() => register()} type="button">Sign up</button><button onClick={() => login()} type="button">Sign In</button>You can also pass additional parameters to the auth URL.
Passing additional params to the auth URL
Link to this sectionBoth the login and register methods accept all the extra authentication params that can be passed to Kinde as part of the auth flow:
loginHint- this allows you to ask Kinde to prepopulate a user’s email address on the sign-up and sign-in screens.lang- if you offer multi-language support, Kinde will automatically figure out the best language for your user based on their browser. However, if you want to force a language and override the user’s preference, you can do so by passing this attribute.
<button onClick={() => login({ loginHint: "jenny@example.com", lang: "ru" })} type="button">Sign In</button>You can use these params as attributes to the LoginLink and RegisterLink components as well.
<LoginLink loginHint="jenny@example.com" lang="ru"> Sign In</LoginLink>See the login API reference for more available parameters for both login and register methods.
Callback Events
Link to this sectionTo handle the result of authentication, there are three callback events.
onSuccess- On successful authentication, this includes the authenticated user along with the passed state and context to the Kinde hookonError- When an error occurs during authentication, this includes the error along with the passed state and context to the Kinde hookonEvent- When an event occurs during authentication, this includes the event along with the passed state and context to the Kinde hook
<KindeProvider callbacks={ { onSuccess: (user, state, context) => console.log("onSuccess", user, state, context), onError: (error, state, context) => console.log("onError", error, state, context), onEvent: (event, state, context) => console.log("onEvent", event, state, context), } }> <Routes /></KindeProvider>Signing out
Link to this sectionSimilar to sign-in and sign-up, Kinde also provides the logout method and LogoutLink component which can be used to end the current session.
Link component:
import { LogoutLink } from '@kinde-oss/kinde-auth-react/components';
<LogoutLink>Sign out</LogoutLink>Hook method:
const { logout } = useKindeAuth();
<button onClick={() => logout()} type="button">Sign out</button>Portal link
Link to this sectionThe PortalLink component provides a link to the Kinde portal where users can manage their account settings. Learn more about self-serve portal for users.
Link component:
import { PortalLink } from '@kinde-oss/kinde-auth-react/components';
<PortalLink returnPath="/dashboard">Manage account</PortalLink>Hook method:
const { generatePortalUrl } = useKindeAuth();
const handlePortalClick = async () => { const { url } = await generatePortalUrl({ returnPath: "/dashboard" }); window.location.href = url.toString();};
<button onClick={handlePortalClick} type="button">Manage account</button>Test sign-up
Link to this sectionRegister your first user by signing up yourself. You’ll see your newly registered user on the Users page in Kinde.
View user profile
Link to this sectionYou can get an authorized user’s profile from any component using the Kinde React hook.
import { useKindeAuth } from '@kinde-oss/kinde-auth-react';
const Profile = () => { const { user } = useKindeAuth(); return ( <div> <h2>{user?.givenName} {user?.familyName}</h2> <p>{user?.email}</p> </div> )};Check if user is authenticated
Link to this sectionTo be on the safe side, we have also provided isAuthenticated and isLoading state to prevent rendering errors.
import { useKindeAuth } from '@kinde-oss/kinde-auth-react';
const Profile = () => { const { user, isAuthenticated, isLoading } = useKindeAuth();
if (isLoading) { return <p>Loading</p>; }
return ( isAuthenticated ? <div> <h2>{user?.givenName} {user?.familyName}</h2> <p>{user?.email}</p> </div> : <p>Please sign in or register!</p> );};Advanced access control
Link to this sectionThere are two ways to check if a user has a specific permission:
- Using the
hasfunction from the@kinde-oss/kinde-auth-react/utilspackage - Using the
<ProtectedRoute>component
Using the has function
Link to this sectionThe has function is a helper function that checks if a user has specific roles, permissions, feature flags, or billing entitlements. It returns a boolean value indicating whether the user meets all the specified criteria.
import { has } from '@kinde-oss/kinde-auth-react/utils';
// Basic usage - check multiple criteria at onceconst userHasAccess = has({ roles: ['admin'], permissions: ['create:todos'], featureFlags: ['theme'], billingEntitlements: ['premium']});Parameters:
roles(optional): Array of role names the user must havepermissions(optional): Array of permission names the user must havefeatureFlags(optional): Array of feature flag names the user must havebillingEntitlements(optional): Array of billing entitlement names the user must have
Return value: boolean - true if user meets all criteria, false otherwise
API vs Token-based checks
Link to this sectionBy default, the has function performs checks using the user’s tokens. You can override this behavior by passing the forceApi option to perform server-side validation:
// Force all checks to use API calls instead of tokenshas({ roles: ['admin'], permissions: ['create:todos'], forceApi: true})
// Force only specific checks to use API callshas({ roles: ['admin'], permissions: ['create:todos'], forceApi: { permissions: true } // Only permissions use API, roles use tokens})Advanced usage with conditions
Link to this sectionYou can add custom conditions to any check by expanding the object structure:
// Add custom conditions to role checkshas({ roles: [{ role: 'admin', condition: (user) => user.isAdmin && user.isActive }],})
// Add custom conditions to permission checkshas({ permissions: [{ permission: 'create:todos', condition: (user) => user.organizationId === 'org123' }],})Feature flag value checking
Link to this sectionFor feature flags, you can check both the flag’s existence and its specific value:
// Check if feature flag existshas({ featureFlags: ['theme']})
// Check if feature flag has a specific valuehas({ featureFlags: [{ flag: 'theme', value: 'dark' }]})
// Check multiple feature flags with valueshas({ featureFlags: [ { flag: 'theme', value: 'dark' }, { flag: 'beta_features', value: true } ]})Complete example
Link to this sectionimport { has } from '@kinde-oss/kinde-auth-react/utils';
const checkUserAccess = () => { const canAccessAdminPanel = has({ roles: ['admin', 'super_admin'], permissions: ['read:users', 'write:users'], featureFlags: ['admin_panel'], billingEntitlements: ['enterprise_plan'] });
const canUseDarkTheme = has({ featureFlags: [{ flag: 'theme', value: 'dark' }], permissions: ['customize:theme'] });
return { canAccessAdminPanel, canUseDarkTheme };};TypeScript type safety
Link to this sectionYou can enhance type safety by declaring your specific roles, permissions, feature flags, and billing entitlements. This provides autocomplete and compile-time checking for your access control.
Create a type declaration file (e.g., kinde-types.d.ts) in your project:
declare module "@kinde-oss/kinde-auth-react/utils" { interface KindeConfig { roles: ['admin', 'user', 'moderator', 'super_admin']; permissions: ['read:users', 'write:users', 'delete:users', 'manage:settings']; featureFlags: ['dark_mode', 'beta_features', 'admin_panel']; billingEntitlements: ['basic', 'premium', 'enterprise']; }}Note: Make sure your tsconfig.json includes the type declaration file, or place it in a directory that TypeScript automatically includes (like src/types/ or the root of your project).
Using the <ProtectedRoute> component
Link to this sectionNote: The <ProtectedRoute> component requires the react-router-dom package to be installed.
The <ProtectedRoute> component is a wrapper component that checks if a user has specific permissions and renders the child component if they do. If the user doesn’t have the required permissions, they are redirected to a fallback path.
import { ProtectedRoute } from '@kinde-oss/kinde-auth-react/react-router';
// Basic usage - protect a route with role-based access<ProtectedRoute has={{ roles: ['admin'] }} fallbackPath="/"> <div>You have access to this admin page</div></ProtectedRoute>Props:
has(required): Object containing the access requirements (same format as thehasfunction)fallbackPath(optional): Path to redirect to if user doesn’t have access. Defaults to/if not provided.children(required): React components to render if user has access
Basic examples
Link to this section// Protect with single role<ProtectedRoute has={{ roles: ['admin'] }} fallbackPath="/unauthorized"> <AdminDashboard /></ProtectedRoute>
// Protect with multiple roles (user must have at least one)<ProtectedRoute has={{ roles: ['admin', 'moderator'] }} fallbackPath="/"> <ModeratorPanel /></ProtectedRoute>
// Protect with permissions<ProtectedRoute has={{ permissions: ['read:users', 'write:users'] }} fallbackPath="/dashboard"> <UserManagement /></ProtectedRoute>
// Protect with feature flags<ProtectedRoute has={{ featureFlags: ['beta_features'] }} fallbackPath="/"> <BetaFeatures /></ProtectedRoute>Complex access control
Link to this section// Multiple criteria - user must have ALL specified requirements<ProtectedRoute has={{ roles: ['admin'], permissions: ['manage:users'], featureFlags: ['admin_panel'], billingEntitlements: ['premium'] }} fallbackPath="/upgrade"> <PremiumAdminPanel /></ProtectedRoute>
// Using API-based checks for real-time validation<ProtectedRoute has={{ roles: ['admin'], permissions: ['manage:users'], forceApi: true }} fallbackPath="/"> <RealTimeAdminPanel /></ProtectedRoute>Integration with React Router
Link to this sectionimport { Routes, Route } from 'react-router-dom';import { ProtectedRoute } from '@kinde-oss/kinde-auth-react/react-router';
function App() { return ( <Routes> <Route path="/" element={<HomePage />} /> <Route path="/admin" element={ <ProtectedRoute has={{ roles: ['admin'] }} fallbackPath="/"> <AdminPage /> </ProtectedRoute> } /> <Route path="/premium" element={ <ProtectedRoute has={{ billingEntitlements: ['premium'] }} fallbackPath="/upgrade" > <PremiumPage /> </ProtectedRoute> } /> </Routes> );}Complete example with multiple protected routes
Link to this sectionimport { Routes, Route } from 'react-router-dom';import { ProtectedRoute } from '@kinde-oss/kinde-auth-react/react-router';
function App() { return ( <Routes> <Route path="/" element={<HomePage />} />
{/* Basic admin access */} <Route path="/admin" element={ <ProtectedRoute has={{ roles: ['admin'] }} fallbackPath="/"> <AdminDashboard /> </ProtectedRoute> } />
{/* Premium features */} <Route path="/premium" element={ <ProtectedRoute has={{ billingEntitlements: ['premium'] }} fallbackPath="/upgrade" > <PremiumFeatures /> </ProtectedRoute> } />
{/* Beta features with specific permissions */} <Route path="/beta" element={ <ProtectedRoute has={{ featureFlags: ['beta_access'], permissions: ['beta:test'] }} fallbackPath="/" > <BetaFeatures /> </ProtectedRoute> } /> </Routes> );}Call your API
Link to this sectionThe getAccessToken method lets you securely call your API and pass the bearer token to validate that your user is authenticated.
const { getAccessToken } = useKindeAuth();
const fetchData = async () => { try { const accessToken = await getAccessToken(); const res = await fetch(`<your-api>`, { headers: { Authorization: `Bearer ${accessToken}` } }); const {data} = await res.json(); console.log({data}); } catch (err) { console.log(err); }};We have a range of backend SDKs available to assist you in securing your backend application using this token. Alternatively, you can use any JWT validator and decoder to assist you here.
Audience
Link to this sectionThe audience is the intended recipient of an access token - for example, the API for your application. The audience argument can be passed to the Kinde client to request an audience be added to the provided token.
<KindeProvider audience="<your_api>">To request multiple audiences, pass them separated by whitespace.
<KindeProvider audience="<your_api1> <your_api2>">For details on how to connect, see Register an API.
Organizations
Link to this sectionCreate an organization
Link to this sectionTo create a new organization with the user registration, you can use the isCreateOrg parameter in the login method to start the registration process:
<LoginLink isCreateOrg={true}>Sign in</LoginLink><button onClick={() => login({isCreateOrg: true})} type="button">Sign In</button>Sign up/sign in users to organizations
Link to this sectionTo sign up a user to a particular organization, you must pass the orgCode from your Kinde account as the user is created. You can find the orgCode on the Details page of each organization in Kinde.
<LoginLink orgCode="org_1234">Sign in</LoginLink><button onClick={() => login({orgCode: "org_1234"})} type="button">Sign In</button>Following authentication, Kinde provides a JSON Web Token (JWT) to your application. Along with the standard information, we also include the org_code and the permissions for that organization (this is important as a user can belong to multiple organizations and have different permissions for each). Example of a returned token:
{ "aud": ["https://your_subdomain.kinde.com"], "exp": 1658475930, "iat": 1658472329, "iss": "https://your_subdomain.kinde.com", "jti": "123457890", "org_code": "org_1234", "permissions": ["read:todos", "create:todos"], "scp": ["openid", "offline"], "sub": "kp:123457890"}For more information about how organizations work in Kinde, see Kinde organizations for developers.
User Permissions
Link to this sectionOnce a user has been verified as signed in, your project/application will receive a JWT token containing an array of permissions for that user. You need to configure your project to read permissions and unlock the respective functions.
Configure permissions in Kinde first. Here is an example set of permissions.
"permissions":[ "create:todos", "update:todos", "read:todos", "delete:todos", "create:tasks", "update:tasks", "read:tasks", "delete:tasks"]We provide helper functions to more easily access permissions:
const {getPermission, getPermissions} = useKindeAuth();
await getPermission("create:todos");// {permissionKey: "create:todos", orgCode: "org_1234", isGranted: true}
await getPermissions();// {orgCode: "org_1234", permissions: ["create:todos", "update:todos", "read:todos"]}A practical example in code might look something like:
{ (await getPermission("create:todos")).isGranted ? <button>Create todo</button> : null;}Feature flags
Link to this sectionWhen a user signs in, the access token your project/application receives contains a custom claim called feature_flags which is an object detailing the feature flags for that user.
You can set feature flags in your Kinde account. Here’s an example.
feature_flags: { theme: { "t": "s", "v": "pink" }, is_dark_mode: { "t": "b", "v": true }, competitions_limit: { "t": "i", "v": 5 }}In order to minimize the payload in the token we have used single letter keys / values where possible. The single letters represent the following:
t = type
v = value
s = string
b = boolean
i = integer
We provide helper functions to more easily access feature flags:
const { getFlag } = useKindeAuth();
/* Example usage */await getFlag('theme'); // string valueawait getFlag<boolean>('theme'); // boolean valueawait getFlag<number>('theme'); // numeric value
/*{// "code": "theme",// "type": "string",// "value": "pink",// "is_default": false // whether the fallback value had to be used*/}
getFlag('create_competition', {defaultValue: false});/*{ "code": "create_competition", "value": false, "is_default": true // because fallback value had to be used}*/A practical example in code might look something like:
import { useState, useEffect } from 'react';import { useKindeAuth } from '@kinde-oss/kinde-auth-react';
const CompetitionButton = () => { const { getFlag } = useKindeAuth(); const [canCreateCompetition, setCanCreateCompetition] = useState(false); const [theme, setTheme] = useState('');
useEffect(() => { const checkFlags = async () => { const createFlag = await getFlag<boolean>('create_competition'); const themeFlag = await getFlag('theme'); setCanCreateCompetition(createFlag?.value || false); setTheme(themeFlag?.value || 'default'); }; checkFlags(); }, [getFlag]);
if (canCreateCompetition) { return <button className={`theme-${theme}`}>Create competition</button>; } return null;};Overriding scope
Link to this sectionBy default the JavaScript SDK requests the following scopes:
profileemailofflineopenid
You can override this by passing scope into the <KindeProvider>.
<KindeProvider scope="openid">Getting claims
Link to this sectionWe have provided a helper to grab any claim from your ID or access tokens. The helper defaults to access tokens:
const { getClaim } = useKindeAuth();
await getClaim("aud");// {name: "aud", "value": ["api.yourapp.com"]}
await getClaim("given_name", "idToken");// {name: "given_name", "value": "David"}Persisting authentication state on page refresh or new tab
Link to this sectionYou will find that when you refresh the browser using a front-end based SDK that the authentication state is lost. This is because there is no secure way to persist this in the front-end.
There are two ways to work around this.
- (Recommended) use our Custom Domains feature which then allows us to set a secure, httpOnly first party cookie on your domain.
- (Non-production solution only) If you’re not yet ready to add your custom domain, or for local development, we offer an escape hatch
<KindeProvider>useInsecureForRefreshToken. This will use local storage to store the refresh token. DO NOT use this in production.
Once you implement one of the above, you don’t need to do anything else.
Persisting application state
Link to this sectionThe options argument passed into the login and register methods accepts a state key where you can pass in the current application state prior to redirecting to Kinde. This is then returned to you in the second argument of the onSuccess callback as seen above.
A common use case is to allow redirects to the page the user was trying to access prior to authentication. This could be achieved as follows:
Login handler:
<button onClick={() => login({ state: { redirectTo: location.state ? location.state?.from?.pathname : null } }) }/>Redirect handler:
<KindeProvider callbacks={ { onSuccess: (user, state, context) => { window.location = state?.redirectTo }, } }>Token storage in the authentication state
Link to this sectionBy default the JWTs provided by Kinde are stored in memory. This protects you from both CSRF attacks (possible if stored as a client-side cookie) and XSS attacks (possible if persisted in local storage).
The trade-off with this approach, however, is that if a page is refreshed or a new tab is opened, then the token is wiped from memory, and the sign-in button would need to be clicked to re-authenticate. There are two ways to prevent this behavior:
-
Use the Kinde custom domain feature. We can then set a secure,
httpOnlycookie against your domain containing only the refresh token. This reduces token exposure to JavaScript; CSRF protection still relies on controls such as SameSite and server-side request validation. -
There is an escape hatch which can be used for local development:
useInsecureForRefreshToken. This SHOULD NOT be used in production. We recommend you use a custom domain. This will store only the refresh token in local storage and is used to silently re-authenticate.
<KindeProvider useInsecureForRefreshToken={process.env.NODE_ENV === 'development'} ...>API References - KindeProvider
Link to this sectionaudience
Link to this sectionThe audience claim for the JWT.
Type: string
Required: No
clientId
Link to this sectionThe ID of your application as it appears in Kinde.
Type: string
Required: Yes
domain
Link to this sectionEither your Kinde instance URL or your custom domain. e.g. https://yourapp.kinde.com
Type: string
Required: Yes
logoutUri
Link to this sectionWhere your user will be redirected when they log out.
Type: string
Required: No
useInsecureForRefreshToken
Link to this sectionAn escape hatch for storing the refresh in local storage for local development.
Type: boolean
Required: No
Default: false
redirectUri
Link to this sectionThe URL that the user will be returned to after authentication.
Type: string
Required: Yes
scope
Link to this sectionThe scopes to be requested from Kinde.
Type: string
Required: No
Default: openid profile email offline
API References - useKindeAuth hook
Link to this sectionisAuthenticated
Link to this sectionReturns true if the user is authenticated.
Usage:
const { isAuthenticated } = useKindeAuth();
return <p>{isAuthenticated ? "Welcome user!" : "Please sign in or register!"}</p>;isLoading
Link to this sectionUtility property for avoiding React rendering errors.
Usage:
const { isLoading } = useKindeAuth();
return <p>{isLoading ? "Loading..." : "Loaded"}</p>;Returns the profile object of the currently logged-in user.
Available properties:
id(string) - The user’s Kinde ID (kp_1234567890)givenName(string) - The user’s first namefamilyName(string) - The user’s last nameemail(string) - The user’s emailpicture(string) - The user’s profile picture if available
Usage:
const { user } = useKindeAuth();
return ( <div> <h1>{user.givenName} {user.familyName}</h1> <p>{user.email}</p> <img src={user.picture} alt="User profile" /> </div>)login
Link to this sectionConstructs redirect URL and sends user to Kinde to sign in.
Arguments:
loginHint?: string;lang?: string;Usage:
<button onClick={() => login({ loginHint: "jenny@example.com", lang: "ru"})}>Sign In</button>All available arguments. These are the same as the register method:
The provider prop KindeProvider.redirectUri is the default redirect (used when you don’t override it). The auth methods login(), register(), and logout() accept method-specific options that can override it: login() and register() use redirectURL per LoginMethodParams (from @kinde/js-utils); logout() uses redirectUrl. Use these exact symbols for each context.
audience(string | string[]) - Audience to include in the tokenclientId(string) - Client ID of the application. This can be found in the application settings in the Kinde dashboardcodeChallenge(string) - Code challenge for PKCEcodeChallengeMethod(string) - Code challenge method for PKCEconnectionId(string) - Connection ID to use for the login. This is found in the authentication settings in the Kinde dashboardisCreateOrg(boolean) - Whether the user is creating an organization on registrationlang(string) - Language to use for the login in 2-letter ISO formatloginHint(string) - Login hint to use for the login. Can be in formats:joe@blogs.com,phone:+447700900000:gb, orusername:joebloggsorgCode(string) - Organization code to use for the loginorgName(string) - Organization name to be used when creating an organization at registrationprompt(PromptTypes) - Prompt to use for the login:login(force re-authentication)create(show registration screen)none(silently authenticate)
redirectURL(string) - Redirect URL to use for the loginresponseType(string) - Response type to use for the login. Kinde currently only supportscodescope(Scopes[]) - Scopes to include in the token:email,profile,openid,offlinestate(object) - State to use for the loginhasSuccessPage(boolean) - Whether to show the success screen at the end of the flow. This is most useful when the callback is not a webpagenonce(string) - Single use code to prevent replay attacksworkflowDeploymentId(string) - Workflow Deployment ID to trigger on authenticationproperties(T & KindeProperties) - Properties to be passedsupportsReauth(boolean) - Define if the auth instigator supports reauth on expired flowsreauthState(string) - Base64 encoded auth parametersplanInterest(string) - Plan the user has indicated interest inpricingTableKey(string) - Key for the pricing table to usepagesMode("preview") - Configuration mode for custom code pages
register
Link to this sectionConstructs redirect URL and sends user to Kinde to sign up.
Arguments:
loginHint?: string;lang?: string;Usage:
<button onClick={() => register({ loginHint: "jenny@example.com", lang: "ru"})}>Sign Up</button>Parameters are the same as the login method.
logout
Link to this sectionLogs the user out of Kinde.
Arguments:
allSessions?: boolean;redirectUrl?: string;Usage:
<button onClick={() => logout({ allSessions: true, redirectUrl: "https://example.com"})}>Sign Out</button>getUserProfile
Link to this sectionReturns the profile for the current user.
Usage:
const { getUserProfile } = useKindeAuth();
const runAsyncFunction = async () => { const profile = await getUserProfile(); console.log(profile);}<button onClick={runAsyncFunction}>Get User Profile</button>Output:
{ id: "kp_1234567890", givenName: "Dave", familyName: "Smith", email: "dave@smith.com", picture: "public_image_url"}getAccessToken
Link to this sectionReturns the raw Access token from memory. This is the recommended method for accessing tokens.
Usage:
const { getAccessToken } = useKindeAuth();
const runAsyncFunction = async () => { const token = await getAccessToken(); console.log(token);}
<button onClick={runAsyncFunction}>Get Access Token</button>Output:
eyJhbGciOiJIUzI1NiIsInR5c...getIdToken
Link to this sectionReturns the raw ID token from memory.
Usage:
const { getIdToken } = useKindeAuth();
const runAsyncFunction = async () => { const idToken = await getIdToken(); console.log(idToken);}
<button onClick={runAsyncFunction}>Get ID Token</button>Output:
eyJhbGciOiJIUzI1NiIsInR5c...getToken (Deprecated)
Link to this sectionDeprecated: Use getAccessToken instead.
Returns the raw Access token from memory.
Usage:
const { getToken } = useKindeAuth();
const runAsyncFunction = async () => { const token = await getToken(); console.log(token);}<button onClick={runAsyncFunction}>Get Token</button>Output:
eyJhbGciOiJIUzI1NiIsInR5c...refreshToken
Link to this sectionManually refresh the access token and get new token values.
Usage:
const { refreshToken } = useKindeAuth();
const runAsyncFunction = async () => { const tokenResult = await refreshToken({ clientId: "your_client_id", domain: "https://your_kinde_domain.kinde.com", }); console.log(tokenResult);}<button onClick={runAsyncFunction}>Refresh Tokens</button>Output:
{ success: true, accessToken: "<access_token>", idToken: "<id_token>", refreshToken: "<refresh_token>"}getFlag
Link to this sectionGet a feature flag value from the feature_flags claim of the access token.
Arguments:
code: string, options?: { defaultValue?: string | boolean | number; type?: "string" | "boolean" | "number"; }Usage:
const { getFlag } = useKindeAuth();
const runAsyncFunction = async () => { const flag = await getFlag("theme"); console.log(flag);}
<button onClick={runAsyncFunction}>Get Flag</button>Output:
{ "code": "theme", "type": "string", "value": "pink", "is_default": false}getClaim
Link to this sectionGet a single claim from an access or ID token.
Arguments:
claim: string, tokenKey?: "accessToken" | "idToken"Usage:
const { getClaim } = useKindeAuth();
const runAsyncFunction = async () => { const claim = await getClaim("given_name", "idToken"); console.log(claim);}
<button onClick={runAsyncFunction}>Get Claim</button>getClaims
Link to this sectionReturns all claims from the access or ID token.
Arguments:
tokenKey?: "accessToken" | "idToken"Usage:
const { getClaims } = useKindeAuth();
const runAsyncFunction = async () => {
const claims = await getClaims(); // or const idTokenClaims = await getClaims("idToken"); console.log(claims);}
<button onClick={runAsyncFunction}>Get Claims</button>getOrganization
Link to this sectionGet the ID of the organization your user is signed into.
Usage:
const { getOrganization } = useKindeAuth();
const runAsyncFunction = async () => { const org = await getOrganization(); console.log(org);}<button onClick={runAsyncFunction}>Get Organization</button>Output:
org_1234getCurrentOrganization
Link to this sectionGet the ID of the organization your user is signed into. This is an alias for getOrganization.
Usage:
const { getCurrentOrganization } = useKindeAuth();
const runAsyncFunction = async () => { const org = await getCurrentOrganization(); console.log(org);}<button onClick={runAsyncFunction}>Get Current Organization</button>Output:
org_1234getUserOrganizations
Link to this sectionGets an array of all organizations the user has access to.
Usage:
const { getUserOrganizations } = useKindeAuth();
const runAsyncFunction = async () => { const orgs = await getUserOrganizations(); console.log(orgs);}
<button onClick={runAsyncFunction}>Get User Organizations</button>Output:
["org_1234", "org_5678"]getRoles
Link to this sectionReturns all roles for the current user for the organization they are signed into.
Usage:
const { getRoles } = useKindeAuth();
const runAsyncFunction = async () => { const roles = await getRoles(); console.log(roles);}<button onClick={runAsyncFunction}>Get Roles</button>Output:
{ orgCode: "org_1234", roles: ["admin", "user"]}getPermission
Link to this sectionReturns the state of a given permission.
Arguments:
key: string;Usage:
const { getPermission } = useKindeAuth();
const runAsyncFunction = async () => { const permission = await getPermission("read:todos"); console.log(permission);}<button onClick={runAsyncFunction}>Get Permission</button>Output:
{ permissionKey: "read:todos", orgCode: "org_1234", isGranted: true}getPermissions
Link to this sectionReturns all permissions for the current user for the organization they are signed into.
Usage:
const { getPermissions } = useKindeAuth();
const runAsyncFunction = async () => { const permissions = await getPermissions(); console.log(permissions);}<button onClick={runAsyncFunction}>Get Permissions</button>Output:
{ orgCode: "org_1234", permissions: [ "create:todos", "update:todos", "read:todos" ]}generatePortalUrl
Link to this sectionGenerates a URL for the Kinde portal. You can also use the <PortalLink /> component to redirect the user to the portal. Learn more about self-serve portal for users.
Arguments:
options: { returnPath?: string; orgCode?: string;}Usage:
const { generatePortalUrl } = useKindeAuth();
const handlePortalClick = async () => { const { url } = await generatePortalUrl({ returnPath: "/dashboard" }); window.location.href = url.toString();};
<button onClick={handlePortalClick} type="button">Manage account</button>Migrate from V4 to V5
Link to this sectionLogin and register method params
Link to this sectionYou no longer need to use the authUrlParams parameter. All URL params are now passed at the top level and are now camelCase instead of snake_case.
For example:
login({ authUrlParams: { login_hint: "jenny@example.com", lang: "ru" }})becomes
login({ loginHint: "jenny@example.com", lang: "ru"})Callbacks
Link to this sectiononRedirectCallback has been removed in favor of a richer event system.
This has been replaced by callbacks > onSuccess.
Create organization
Link to this sectionThe createOrg method has been removed and replaced by using isCreateOrg on the login or register methods or components.
Accessing access token
Link to this sectiongetToken has been replaced by await getAccessToken().
Token helpers
Link to this sectionAll token helpers are now async methods.
getClaim
Link to this sectionThe second argument of the getClaim method has changed to camelCase.
Before:
getClaim("given_name", "id_token");After:
await getClaim("given_name", "idToken");If you need any assistance with getting Kinde connected, reach out to us at support@kinde.com.