Skip to content
  • SDKs and APIs
  • Front end SDKs

React SDK

The Kinde React SDK allows developers to quickly and securely integrate a new or existing React application to the Kinde platform.

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).

  • A Kinde account (Sign up for free)
  • Node.js version 20 or higher

Set up a Kinde application

Link to this section
  1. Sign in to your Kinde dashboard and select Add application
  2. Enter a name for the application (e.g., “My React App”)
  3. Select Front-end and mobile as the application type, then select Save.
  4. On the Quick start page, select React from the list of Front-end SDKs, then select Save.

react sdk

Using non-production environments

Link to this section

Kinde 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
  1. On the Quick start page, select Set for both callback URL and logout URL. This will set http://localhost:3000 as your default URLs. If you want to use a different URL, you can change it in the Details page.

  2. Download the React starter kit

  3. Go to the root of your project and install the dependencies:

    Terminal window
    cd react-starter-kit
    npm install
  4. Create an environment variable file:

    Terminal window
    cp .env_sample .env
  5. Copy the environment variables from the Quick start page to the .env file and save changes.

  6. Start the development server:

    Terminal window
    npm run dev
  7. Open the browser and navigate to http://localhost:3000 to see the application.

  8. Sign up for a new user.

  9. Go to your Kinde dashboard > Users to find your newly created user.

Option 2: Install for an existing project

Link to this section
  1. On the Quick start page, select Existing codebase and edit your project URL (defaults to http://localhost:3000)

  2. Select Set for both callback URL and logout URL.

  3. Open your project in your terminal and install the Kinde dependency with the following command:

    Terminal window
    npm i @kinde-oss/kinde-auth-react
  4. Import the KindeProvider component and wrap your application in it.

    app.jsx
    import { KindeProvider } from '@kinde-oss/kinde-auth-react';
    const App = () => (
    <KindeProvider
    clientId="<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 section

Sign-in and sign-up

Link to this section

Link 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 section

Both 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 section

To 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 hook
  • onError - When an error occurs during authentication, this includes the error along with the passed state and context to the Kinde hook
  • onEvent - When an event occurs during authentication, this includes the event along with the passed state and context to the Kinde hook
App.jsx
<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>

Similar 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>

The 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>

Register 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 section

You can get an authorized user’s profile from any component using the Kinde React hook.

Profile.jsx
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 section

To be on the safe side, we have also provided isAuthenticated and isLoading state to prevent rendering errors.

Profile.jsx
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 section

There are two ways to check if a user has a specific permission:

  • Using the has function from the @kinde-oss/kinde-auth-react/utils package
  • Using the <ProtectedRoute> component

Using the has function

Link to this section

The 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 once
const userHasAccess = has({
roles: ['admin'],
permissions: ['create:todos'],
featureFlags: ['theme'],
billingEntitlements: ['premium']
});

Parameters:

  • roles (optional): Array of role names the user must have
  • permissions (optional): Array of permission names the user must have
  • featureFlags (optional): Array of feature flag names the user must have
  • billingEntitlements (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 section

By 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 tokens
has({
roles: ['admin'],
permissions: ['create:todos'],
forceApi: true
})
// Force only specific checks to use API calls
has({
roles: ['admin'],
permissions: ['create:todos'],
forceApi: { permissions: true } // Only permissions use API, roles use tokens
})

Advanced usage with conditions

Link to this section

You can add custom conditions to any check by expanding the object structure:

// Add custom conditions to role checks
has({
roles: [{
role: 'admin',
condition: (user) => user.isAdmin && user.isActive
}],
})
// Add custom conditions to permission checks
has({
permissions: [{
permission: 'create:todos',
condition: (user) => user.organizationId === 'org123'
}],
})

Feature flag value checking

Link to this section

For feature flags, you can check both the flag’s existence and its specific value:

// Check if feature flag exists
has({
featureFlags: ['theme']
})
// Check if feature flag has a specific value
has({
featureFlags: [{ flag: 'theme', value: 'dark' }]
})
// Check multiple feature flags with values
has({
featureFlags: [
{ flag: 'theme', value: 'dark' },
{ flag: 'beta_features', value: true }
]
})

Complete example

Link to this section
import { 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 section

You 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 section

Note: 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 the has function)
  • 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 section
import { 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 section
import { 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>
);
}

The 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.

The 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.

Create an organization

Link to this section

To 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 section

To 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 section

Once 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;
}

When 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 value
await getFlag<boolean>('theme'); // boolean value
await 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 section

By default the JavaScript SDK requests the following scopes:

  • profile
  • email
  • offline
  • openid

You can override this by passing scope into the <KindeProvider>.

<KindeProvider
scope="openid"
>

Getting claims

Link to this section

We 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 section

You 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 section

The 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 section

By 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:

  1. Use the Kinde custom domain feature. We can then set a secure, httpOnly cookie 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.

  2. 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 section

The audience claim for the JWT.

Type: string

Required: No

The ID of your application as it appears in Kinde.

Type: string

Required: Yes

Either your Kinde instance URL or your custom domain. e.g. https://yourapp.kinde.com

Type: string

Required: Yes

Where your user will be redirected when they log out.

Type: string

Required: No

useInsecureForRefreshToken

Link to this section

An escape hatch for storing the refresh in local storage for local development.

Type: boolean

Required: No

Default: false

The URL that the user will be returned to after authentication.

Type: string

Required: Yes

The scopes to be requested from Kinde.

Type: string

Required: No

Default: openid profile email offline

API References - useKindeAuth hook

Link to this section

isAuthenticated

Link to this section

Returns true if the user is authenticated.

Usage:

const { isAuthenticated } = useKindeAuth();
return <p>{isAuthenticated ? "Welcome user!" : "Please sign in or register!"}</p>;

Utility 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 name
  • familyName (string) - The user’s last name
  • email (string) - The user’s email
  • picture (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>
)

Constructs 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:

  • audience (string | string[]) - Audience to include in the token
  • clientId (string) - Client ID of the application. This can be found in the application settings in the Kinde dashboard
  • codeChallenge (string) - Code challenge for PKCE
  • codeChallengeMethod (string) - Code challenge method for PKCE
  • connectionId (string) - Connection ID to use for the login. This is found in the authentication settings in the Kinde dashboard
  • isCreateOrg (boolean) - Whether the user is creating an organization on registration
  • lang (string) - Language to use for the login in 2-letter ISO format
  • loginHint (string) - Login hint to use for the login. Can be in formats: joe@blogs.com, phone:+447700900000:gb, or username:joebloggs
  • orgCode (string) - Organization code to use for the login
  • orgName (string) - Organization name to be used when creating an organization at registration
  • prompt (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 login
  • responseType (string) - Response type to use for the login. Kinde currently only supports code
  • scope (Scopes[]) - Scopes to include in the token: email, profile, openid, offline
  • state (object) - State to use for the login
  • hasSuccessPage (boolean) - Whether to show the success screen at the end of the flow. This is most useful when the callback is not a webpage
  • nonce (string) - Single use code to prevent replay attacks
  • workflowDeploymentId (string) - Workflow Deployment ID to trigger on authentication
  • properties (T & KindeProperties) - Properties to be passed
  • supportsReauth (boolean) - Define if the auth instigator supports reauth on expired flows
  • reauthState (string) - Base64 encoded auth parameters
  • planInterest (string) - Plan the user has indicated interest in
  • pricingTableKey (string) - Key for the pricing table to use
  • pagesMode ("preview") - Configuration mode for custom code pages

Constructs 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.

Logs 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 section

Returns 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 section

Returns 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...

Returns 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 section

Deprecated: 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...

Manually 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>"
}

Get 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
}

Get 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>

Returns 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 section

Get 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_1234

getCurrentOrganization

Link to this section

Get 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_1234

getUserOrganizations

Link to this section

Gets 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"]

Returns 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"]
}

Returns 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 section

Returns 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 section

Generates 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 section

Login and register method params

Link to this section

You 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"
})

onRedirectCallback has been removed in favor of a richer event system.

This has been replaced by callbacks > onSuccess.

Create organization

Link to this section

The createOrg method has been removed and replaced by using isCreateOrg on the login or register methods or components.

Accessing access token

Link to this section

getToken has been replaced by await getAccessToken().

All token helpers are now async methods.

The 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.