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

> Integrate Logto with React/Next.js apps using our SDK. Simplify authentication, token refresh, and session management. Get started with our complete guide today.

- Repository: [Logto/logto](https://github.com/logto-io/logto)
- Tags: sdk-guide
- Published: 2026-07-05

---

**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`.

```bash
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`](https://github.com/logto-io/logto/blob/main/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:

```tsx
// 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`](https://github.com/logto-io/logto/blob/main/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:

```tsx
// 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:

```tsx
// 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`](https://github.com/logto-io/logto/blob/main/pages/_app.tsx) as demonstrated in the Logto Console source at [`packages/console/src/App.tsx`](https://github.com/logto-io/logto/blob/main/packages/console/src/App.tsx). The provider functions correctly in both server and client contexts because it only accesses browser APIs after component hydration.

```tsx
// 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`](https://github.com/logto-io/logto/blob/main/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`](https://github.com/logto-io/logto/blob/main/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.