How to Integrate Logto with React/Next.js Applications: Complete SDK Guide

The @logto/react SDK provides a LogtoProvider context and useLogto hook that abstracts OIDC flows, automatic token refresh, and session management for React and Next.js applications.

Integrating authentication into modern React applications requires handling complex OpenID Connect flows, secure token storage, and session persistence. The logto-io/logto repository ships a first-class React SDK that eliminates this boilerplate through a declarative provider pattern. This guide demonstrates how to implement Logto authentication in both single-page React applications and Next.js projects using patterns derived from the official Logto monorepo source code.

Install the Logto React SDK

Begin by adding the official SDK to your project dependencies. The package is maintained within the packages/react directory of the Logto monorepo and published as @logto/react.

npm install @logto/react

# or

pnpm add @logto/react

Configure LogtoProvider for React Applications

The LogtoProvider component creates a React context that initializes the Logto client, persists tokens in localStorage, and manages automatic token refresh. According to the implementation in packages/demo-app/src/App.tsx, the provider expects a LogtoConfig object containing your Logto endpoint, application ID, and optional parameters such as scopes and resources.

Wrap your application root with the provider:

// src/App.tsx
import { LogtoProvider, type LogtoConfig } from '@logto/react';
import Main from './Main';

const config: LogtoConfig = {
  endpoint: 'https://my-logto-instance.com',
  appId: 'your-app-id', // Obtain from Logto admin console
  // Optional: prompt, scopes, resources
};

export default function App() {
  return (
    <LogtoProvider config={config}>
      <Main />
    </LogtoProvider>
  );
}

The provider defers browser API access until after hydration, ensuring compatibility with server-side rendering environments.

Implement Authentication Flows with useLogto

The useLogto hook exposes the authentication state and primary interaction methods. As implemented in the demo application at packages/demo-app/src/App.tsx (lines 23-25), this hook provides:

  • signIn(options?) – Redirects the user to Logto’s hosted sign-in page
  • signOut(redirectUri?) – Clears stored tokens and optionally redirects after logout
  • isAuthenticated – Boolean indicating active session status
  • isLoading – Boolean for initial authentication state recovery
  • getIdTokenClaims() – Returns decoded ID token claims containing user profile data

Implement sign-in and sign-out buttons in your components:

// src/pages/Home.tsx
import { useLogto } from '@logto/react';

export default function Home() {
  const { isAuthenticated, signIn, signOut, getIdTokenClaims } = useLogto();

  return (
    <div>
      {isAuthenticated ? (
        <button onClick={() => signOut('/')}>Sign out</button>
      ) : (
        <button onClick={() => signIn('/')}>Sign in</button>
      )}

      {isAuthenticated && (
        <div>
          <h2>User Profile</h2>
          <pre>{JSON.stringify(getIdTokenClaims(), null, 2)}</pre>
        </div>
      )}
    </div>
  );
}

Handle OAuth Callbacks in React

After successful authentication, Logto redirects users to a registered callback URL with authorization parameters. The SDK provides useHandleSignInCallback to complete the token exchange, verify state parameters, and clean up temporary query strings.

Create a dedicated callback route:

// src/pages/callback.tsx
import { useHandleSignInCallback } from '@logto/react';
import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function Callback() {
  const { isLoading } = useHandleSignInCallback(() => {
    const router = useRouter();
    router.replace('/');
  });

  return isLoading ? <p>Completing authentication...</p> : null;
}

Important: You must register the callback URL (e.g., https://my-site.com/callback) in the Logto admin console under your application's Redirect URIs configuration.

Next.js Integration Strategies

For Next.js applications using the Pages Router, initialize the provider in pages/_app.tsx as demonstrated in the Logto Console source at packages/console/src/App.tsx. The provider functions correctly in both server and client contexts because it only accesses browser APIs after component hydration.

// pages/_app.tsx
import type { AppProps } from 'next/app';
import { LogtoProvider } from '@logto/react';

const logtoConfig = {
  endpoint: process.env.NEXT_PUBLIC_LOGTO_ENDPOINT!,
  appId: process.env.NEXT_PUBLIC_LOGTO_APP_ID!,
};

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <LogtoProvider config={logtoConfig}>
      <Component {...pageProps} />
    </LogtoProvider>
  );
}

For complex applications requiring multiple authentication contexts, reference packages/account/src/App.tsx, which demonstrates nested provider patterns for dedicated account management UIs.

Summary

  • Install @logto/react from npm to access the official SDK implemented in the packages/react source directory
  • Wrap your application with LogtoProvider, supplying a LogtoConfig object with your endpoint and app ID
  • Use useLogto to access signIn(), signOut(), and authentication state booleans (isAuthenticated, isLoading)
  • Implement a callback handler using useHandleSignInCallback to complete the OIDC flow and extract user claims via getIdTokenClaims()
  • Configure redirect URIs in the Logto admin console to match your application's callback routes
  • Reference packages/demo-app/src/App.tsx and packages/console/src/assets/docs/guides/spa-react/README.mdx for complete working implementations

Frequently Asked Questions

Does Logto support Next.js App Router?

Yes, the @logto/react SDK works with Next.js App Router by marking the provider component with the 'use client' directive. The SDK defers browser API access until after hydration, preventing server-side rendering errors while maintaining full authentication functionality in client components.

Where does the Logto React SDK store authentication tokens?

The SDK automatically persists tokens in the browser's localStorage. This implementation detail in packages/react ensures tokens survive page refreshes without requiring additional configuration. The provider handles automatic token refresh before expiration, maintaining session continuity.

How do I configure redirect URIs for my React application?

In the Logto admin console, navigate to your application settings and add your callback URL (e.g., http://localhost:3000/callback or https://production-site.com/callback) to the Redirect URIs list. The signIn() method automatically uses the current origin, but the exact path must match a registered URI to prevent OAuth errors.

Can I use Logto authentication with server-side rendering (SSR)?

The LogtoProvider is designed to work with SSR frameworks like Next.js by only accessing browser APIs after component hydration. While the initial render occurs server-side, authentication state is resolved client-side. For server-side token validation in API routes, use the Logto Node SDK (@logto/node) instead of the React SDK.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →