How to Use the Logto SDK for Web Development: A Complete Integration Guide

The Logto SDK wraps OpenID Connect (OIDC) authentication into a promise-based API that handles authorization codes, token storage, and session management with minimal configuration.

The Logto SDK for web development provides a language-agnostic abstraction over the OpenID Connect protocol, enabling developers to add enterprise-grade authentication to web applications using a consistent, framework-agnostic interface. As implemented in the logto-io/logto repository, these SDKs automatically manage authorization codes, token exchanges, and secure storage while exposing a simple client-based API that works across vanilla JavaScript, React, Next.js, SvelteKit, and Vue applications.

Core Concepts of the Logto Web SDK

Every Logto web SDK follows the same architectural pattern, wrapping low-level OIDC flows behind high-level methods. Understanding these core concepts ensures consistent implementation across different frameworks:

  • Client initialization – Create a LogtoClient instance by supplying your Logto tenant's endpoint and appId, with optional custom storage configuration.
  • Redirect URI handling – Define callback URLs where Logto returns users after authentication; these must match entries configured in the Logto Console.
  • Sign-in flow – The signIn(redirectUri) method redirects users to Logto's hosted login page and initiates the authorization code flow.
  • Callback processing – handleSignInCallback(currentUrl) exchanges the authorization code for tokens and securely stores them.
  • Session management – isAuthenticated() checks token validity, while getAccessToken(resource) returns fresh tokens for API calls.
  • Sign-out flow – signOut(postLogoutRedirectUri) clears stored tokens and optionally redirects users to a post-logout page.

The SDK automatically injects required OIDC parameters including client_id, response_type=code, and scope=openid profile email, while supporting extraParams for extensions like ui_locales or organization_id according to the source code in packages/experience/CHANGELOG.md.

Installing the Logto Browser SDK

For vanilla JavaScript or framework-agnostic implementations, install the browser SDK using your preferred package manager or load it directly via CDN:


# npm

npm i @logto/browser

# pnpm

pnpm add @logto/browser

# yarn

yarn add @logto/browser

For applications without a bundler, import the SDK directly from jsDelivr:

<script type="module">
  import LogtoClient from 'https://cdn.jsdelivr.net/npm/@logto/browser@latest/+esm';
</script>

This installation pattern is documented in packages/console/src/assets/docs/guides/spa-vanilla/README.mdx and provides the foundation for all browser-based authentication flows.

Implementing Authentication in Vanilla JavaScript

The following implementation steps reference the definitive vanilla JavaScript guide located at packages/console/src/assets/docs/guides/spa-vanilla/README.mdx.

Initialize the LogtoClient

Import the client and instantiate it with your tenant configuration:

import LogtoClient from '@logto/browser';

const logtoClient = new LogtoClient({
  endpoint: 'https://your-logto-instance.com',
  appId: 'your-app-id',
});

The LogtoClient constructor accepts an endpoint (your Logto tenant URL) and appId (the application ID from the Logto Console), with optional parameters for custom storage adapters.

Configure Redirect URIs

Before invoking authentication methods, register your callback URLs in the Logto Console. The redirect URI used in signIn() must exactly match one of the allowed URIs configured in your application settings (e.g., https://example.com/callback).

Handle the Authentication Callback

After the user authenticates on Logto's hosted page, they return to your application with an authorization code. Extract this code and exchange it for tokens:

const callbackHandler = async (logtoClient) => {
  await logtoClient.handleSignInCallback(window.location.href);

  if (!logtoClient.isAuthenticated) {
    alert('Failed to sign in');
    return;
  }

  // Successful authentication – redirect to home
  window.location.assign('/');
};

The handleSignInCallback() method validates the state parameter, exchanges the code for tokens, and stores them securely according to your storage configuration.

Implement Sign-In and Sign-Out Buttons

Check authentication status and render appropriate UI controls:

const isAuthenticated = await logtoClient.isAuthenticated();

const onClickSignIn = () => {
  logtoClient.signIn('https://example.com/callback');
};

const onClickSignOut = () => {
  logtoClient.signOut('https://example.com/');
};

const button = document.createElement('button');
button.innerHTML = isAuthenticated ? 'Sign Out' : 'Sign In';
button.addEventListener('click', isAuthenticated ? onClickSignOut : onClickSignIn);
document.body.appendChild(button);

The signOut() method clears all stored tokens and, if provided with a postLogoutRedirectUri, redirects the user to the specified location.

Access User Claims

Retrieve decoded ID token claims after successful authentication:

const userInfo = await logtoClient.getIdTokenClaims();
// Returns: { sub, name, email, picture, ... }

For API authorization, request a fresh access token using logtoClient.getAccessToken(resource), where resource specifies the target API resource indicator.

Framework-Specific Integration Guides

While the core LogtoClient API remains consistent, Logto provides framework-specific wrappers that handle Reactivity and server-side rendering concerns:

  • React: packages/console/src/assets/docs/guides/spa-react/README.mdx demonstrates useLogtoClient and useLogtoUser hooks for component-level authentication state.
  • Next.js: packages/console/src/assets/docs/guides/web-next/README.mdx covers server-side initialization and API route protection using @logto/next.
  • SvelteKit: packages/console/src/assets/docs/guides/web-sveltekit/README.mdx provides Svelte-specific store integration patterns.
  • Vue: packages/console/src/assets/docs/guides/spa-vue/README.mdx shows composition API integration for reactive authentication state.
  • Express (Node): packages/console/src/assets/docs/guides/api-express/README.mdx details backend SDK usage for API resource protection.

For Chrome extensions, refer to packages/console/src/assets/docs/guides/spa-chrome-extension/README.mdx, which details required permissions and storage adapters for extension-specific security contexts.

Security Features and Custom Storage

The Logto SDK implements several security measures according to the source code in packages/integration-tests/src/client/index.ts:

  • Token isolation – Access tokens and ID tokens are never exposed in URLs; the SDK stores them using your configured storage mechanism.
  • Automatic token rotation – Refresh tokens are handled automatically by the SDK's internal storage adapter.
  • State parameter validation – The SDK generates and validates state parameters during the callback phase to prevent CSRF attacks.

By default, the SDK uses localStorage for token persistence, but you can provide custom storage adapters to integrate with Express sessions, Chrome extension storage APIs, or secure HTTP-only cookie implementations.

Summary

  • The Logto SDK abstracts OIDC complexity into a LogtoClient class with methods for signIn(), handleSignInCallback(), and signOut().
  • Authentication requires configuring your tenant endpoint and appId, plus registering redirect URIs in the Logto Console.
  • The vanilla JavaScript implementation in packages/console/src/assets/docs/guides/spa-vanilla/README.mdx serves as the reference pattern for all web SDKs.
  • Framework-specific packages (React, Next.js, SvelteKit, Vue) provide idiomatic hooks and components while using the same underlying client.
  • Custom storage adapters allow integration with any session management system, from browser localStorage to server-side Redis stores.

Frequently Asked Questions

What authentication protocol does the Logto SDK use?

The Logto SDK implements the OpenID Connect (OIDC) protocol, specifically the authorization code flow with PKCE. As seen in the source code, the SDK automatically appends required parameters like client_id, response_type=code, and standard scopes (openid profile email) to authentication requests, ensuring standards-compliant security without manual URL construction.

How do I handle the redirect callback in a single-page application?

After the user authenticates, Logto redirects to your specified callback URL with an authorization code. Your application must call logtoClient.handleSignInCallback(window.location.href) on that route to exchange the code for tokens. This method validates the state parameter, stores the tokens securely, and updates the client's authentication status, as demonstrated in packages/console/src/assets/docs/guides/spa-vanilla/README.mdx.

Can I use custom storage instead of localStorage?

Yes. The LogtoClient constructor accepts a custom storage adapter implementing the Storage interface. This allows you to store tokens in Express sessions, Chrome extension storage APIs, or HTTP-only cookies. The SDK uses this adapter for all token persistence, including access tokens, ID tokens, and refresh tokens, making it compatible with any session management architecture.

Which frameworks are officially supported by the Logto SDK?

Logto maintains official SDKs for vanilla JavaScript (@logto/browser), React (@logto/react), Next.js (@logto/next), SvelteKit (@logto/sveltekit), Vue (@logto/vue), and Chrome extensions. Each framework-specific package wraps the core browser client while providing idiomatic patterns—such as React hooks or Svelte stores—for managing authentication state, as documented in the respective guide files under packages/console/src/assets/docs/guides/.

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 →