How to Integrate Logto with React Applications: Complete Implementation Guide
Integrate Logto with React applications by installing the @logto/react SDK, wrapping your application root with <LogtoProvider>, and consuming authentication state through the useLogto() hook to implement secure OpenID Connect flows.
The logto-io/logto repository provides a first-class React SDK that simplifies adding OIDC authentication to single-page applications. When you integrate Logto with React applications, you leverage a context-based architecture that handles token storage, refresh cycles, and secure redirects automatically.
Installing the Logto React SDK
Add the package to your project using your preferred package manager.
npm install @logto/react
For projects using pnpm (the repository's default package manager):
pnpm add @logto/react
Configuring the LogtoProvider
The <LogtoProvider> component injects authentication context throughout your component tree. In packages/demo-app/src/App.tsx and packages/account/src/App.tsx, the provider is configured at the application root to ensure global state availability.
Wrap your root component with the provider, supplying your Logto endpoint and client ID:
// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { LogtoProvider, Prompt } from '@logto/react';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(
<React.StrictMode>
<LogtoProvider
endpoint="https://your-tenant.logto.app"
clientId="YOUR_CLIENT_ID"
// Optional: specify default prompt behavior
// defaultPrompt={Prompt.SignIn}
>
<App />
</LogtoProvider>
</React.StrictMode>
);
Implementing Authentication Flows
Managing Authentication State with useLogto
The useLogto() hook returns the current authentication state and action methods. As implemented in packages/demo-app/src/App.tsx, this hook provides isAuthenticated, isLoading, signIn, signOut, getAccessToken, and getIdTokenClaims.
// src/App.tsx
import { type IdTokenClaims, Prompt, useLogto } from '@logto/react';
export default function App() {
const {
isAuthenticated,
isLoading,
signIn,
signOut,
getIdTokenClaims,
getAccessToken,
} = useLogto();
const handleSignIn = () => {
// Customize the login prompt using the Prompt enum
signIn({ prompt: Prompt.SignIn });
};
const handleShowProfile = async () => {
const claims = await getIdTokenClaims<IdTokenClaims>();
console.log('User profile:', claims);
};
if (isLoading) {
return <div>Loading…</div>;
}
return (
<div>
{isAuthenticated ? (
<>
<button onClick={handleShowProfile}>Show Profile</button>
<button onClick={signOut}>Sign Out</button>
</>
) : (
<button onClick={handleSignIn}>Sign In with Logto</button>
)}
</div>
);
}
Handling the OAuth Callback
After the user authenticates with Logto, they are redirected to your callback URL. The SDK exports useHandleSignInCallback to process this redirect and finalize the login flow, as demonstrated in packages/demo-app/src/Callback.tsx.
Create a dedicated callback component:
// src/Callback.tsx
import { useHandleSignInCallback } from '@logto/react';
export default function Callback() {
// This hook processes the OAuth redirect and stores tokens
useHandleSignInCallback();
return <div>Signing you in…</div>;
}
Accessing Protected Resources
Retrieving User Information
Once authenticated, call getIdTokenClaims() to access the user's profile information stored in the ID token:
const claims = await getIdTokenClaims<IdTokenClaims>();
console.log('User ID:', claims.sub);
console.log('Email:', claims.email);
Calling Protected APIs with Access Tokens
To authenticate requests to your backend API, retrieve an access token using getAccessToken() and include it in the Authorization header:
const fetchProtected = async () => {
const accessToken = await getAccessToken();
const response = await fetch('https://api.myapp.com/protected', {
headers: { Authorization: `Bearer ${accessToken}` },
});
const data = await response.json();
console.log(data);
};
Architectural Patterns from the Logto Repository
The logto-io/logto repository demonstrates production-ready integration patterns across multiple packages:
packages/demo-app/src/App.tsx: Shows minimalLogtoProviderconfiguration anduseLogtoconsumption patterns.packages/demo-app/src/Callback.tsx: Implements the callback handler component usinguseHandleSignInCallback.packages/account/src/App.tsx: Demonstrates real-world administrative UI integration with comprehensive authentication state management.packages/console/src/App.tsx: Illustrates how the Logto console boots authentication for the admin portal interface.
Summary
- Install the
@logto/reactpackage to add Logto authentication capabilities to your React application. - Wrap your application root with
<LogtoProvider>, providing the Logto endpoint and client ID configuration. - Consume authentication state and methods via the
useLogto()hook, which exposessignIn,signOut,getAccessToken, and user claims. - Handle the OAuth callback using
useHandleSignInCallbackto complete the authentication flow and store tokens securely. - Secure your API calls by retrieving access tokens with
getAccessToken()and attaching them to HTTP headers.
Frequently Asked Questions
How does the Logto React SDK store authentication tokens?
According to the logto-io/logto source code in packages/demo-app/src/App.tsx, tokens are persisted in the browser using session or local storage mechanisms. The SDK automatically manages refresh token flows to maintain session validity without requiring re-authentication.
Can I customize the login prompt when calling signIn?
Yes. The signIn() method accepts an optional configuration object including the prompt parameter. You can use the Prompt enum (such as Prompt.SignIn or Prompt.Register) to control whether the user sees the login screen, registration screen, or consent screen during the authentication flow.
What is the difference between getAccessToken and getIdTokenClaims?
getAccessToken() returns the access token used to authorize requests to protected APIs, while getIdTokenClaims() returns the decoded claims from the ID token containing user profile information like email, name, and user ID. Access tokens are for API authorization; ID tokens are for user identity verification.
Do I need to handle the callback route separately?
Yes. You must implement a dedicated callback route that renders a component using the useHandleSignInCallback hook. This component processes the OAuth redirect URL parameters, exchanges the authorization code for tokens, and completes the authentication handshake before redirecting to your main application.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →