How to Integrate Logto with Your Application: A Complete Implementation Guide
Integrate Logto with your application by deploying a Logto instance, creating an application in the Logto Console to obtain a Client ID, installing the appropriate framework SDK, and initializing the provider with your endpoint credentials to handle OpenID Connect authentication flows automatically.
Logto is an open-source authentication platform that implements OIDC, OAuth 2.1, and SAML protocols, providing a complete identity infrastructure for web applications, mobile apps, and API services. When you integrate Logto, you interact with three core architectural components: the Core server (OIDC provider), Connectors (social/SMS providers), and SDKs (client-side libraries). This guide references the official logto-io/logto repository to walk you through the exact implementation steps and file locations needed to add secure authentication to your stack.
Understanding Logto Architecture
Before writing integration code, understand how Logto’s components interact:
-
Core Server: Located in
packages/core/README.md, this is the OIDC provider that handles token issuance, tenant management, RBAC, and the user database. It exposes the endpoints your SDK will call. -
Connectors: Found under
packages/connectors/, these are micro-services that exchange OAuth codes or SMS tokens for Logto access tokens. For example,packages/connectors/connector-google/README.mdcontains the implementation details for Google sign-in. -
SDKs and UI Libraries: The client-side wrappers live in
packages/console/README.md(admin-console integration guides) andpackages/elements/README.md(UI components). These handle redirect logic, token storage, and automatic refresh.
Step-by-Step Integration Process
1. Deploy a Logto Instance
Choose your deployment method based on your environment. The root README.md contains quick-start commands for Docker Compose:
docker compose up -d
Alternatively, use the hosted Logto Cloud or spin up a GitPod demo for testing. Ensure your instance is accessible via HTTPS before configuring applications.
2. Create an Application in the Logto Console
Log in to your Logto Console and create a new application. Select the appropriate type:
- SPA (Single Page Application)
- Traditional Web
- Native
- Machine-to-Machine
The Console will generate a Client ID and (for confidential clients) a Client Secret. Store these securely; you will pass them to the SDK initialization.
3. Configure Social Connectors (Optional)
To enable social sign-in, add a connector such as Google. The configuration lives in packages/connectors/connector-google/README.md, which explains how to:
- Create OAuth 2.0 credentials in the Google Cloud Console.
- Paste the
clientIdandclientSecretinto the Logto Connector settings. - Enable Store tokens for persistent API access if you need to call provider APIs (e.g., Google Drive) later; Logto will store these in its Secret Vault.
4. Add the Logto SDK to Your Application
Install the SDK matching your framework:
- React:
@logto/react - Next.js:
@logto/nextjs - Vue:
@logto/vue
Initialize the provider with your endpoint and Client ID. The SDK automatically manages redirects to the Logto sign-in page and handles callback URLs.
5. Protect Routes and API Calls
Use the SDK’s hooks or HOCs to guard routes. Retrieve access tokens via getAccessToken() or useAccessToken() and attach them as Authorization: Bearer headers to your API requests.
Code Implementation Examples
React SPA Integration
Install the React SDK and wrap your application with LogtoProvider. The implementation references components from packages/elements and packages/experience.
// src/index.tsx – initialise Logto
import { LogtoProvider } from '@logto/react';
import App from './App';
const endpoint = 'https://your-logto-instance.com';
const clientId = 'your-spa-client-id';
ReactDOM.render(
<LogtoProvider endpoint={endpoint} clientId={clientId}>
<App />
</LogtoProvider>,
document.getElementById('root')
);
Protect individual pages using the useLogto hook to check authentication status and fetch tokens:
// src/App.tsx – protect a page
import { useLogto } from '@logto/react';
import { useEffect, useState } from 'react';
function Protected() {
const { isAuthenticated, getAccessToken, signIn } = useLogto();
const [profile, setProfile] = useState(null);
useEffect(() => {
if (isAuthenticated) {
(async () => {
const token = await getAccessToken();
const res = await fetch('/api/me', {
headers: { Authorization: `Bearer ${token}` },
});
setProfile(await res.json());
})();
}
}, [isAuthenticated]);
if (!isAuthenticated) return <button onClick={signIn}>Sign in</button>;
return profile ? <pre>{JSON.stringify(profile, null, 2)}</pre> : <p>Loading…</p>;
}
Next.js Integration
For server-side rendered applications, use @logto/nextjs. The provider wraps your _app.tsx, while withLogto handles server-side token validation:
// pages/_app.tsx – Logto wrapper
import { LogtoProvider } from '@logto/nextjs';
import type { AppProps } from 'next/app';
const endpoint = process.env.NEXT_PUBLIC_LOGTO_ENDPOINT!;
const clientId = process.env.NEXT_PUBLIC_LOGTO_CLIENT_ID!;
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<LogtoProvider endpoint={endpoint} clientId={clientId}>
<Component {...pageProps} />
</LogtoProvider>
);
}
Fetch the access token server-side using getAccessToken inside getServerSideProps:
// pages/profile.tsx – server‑side token fetch
import { getAccessToken, withLogto } from '@logto/nextjs';
export const getServerSideProps = withLogto(async (ctx) => {
const accessToken = await getAccessToken(ctx);
const res = await fetch(`${process.env.LOGTO_API}/api/me`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
const profile = await res.json();
return { props: { profile } };
});
export default function Profile({ profile }: { profile: any }) {
return <pre>{JSON.stringify(profile, null, 2)}</pre>;
}
Machine-to-Machine Authentication
For backend services communicating with protected APIs, use the @logto/node client (located in packages/toolkit) to execute the client-credentials flow:
import { createClient } from '@logto/node';
import fetch from 'node-fetch';
const logto = createClient({
endpoint: 'https://your-logto-instance.com',
clientId: 'm2m-client-id',
clientSecret: 'm2m-client-secret',
});
async function callProtectedApi() {
const token = await logto.getAccessToken(); // obtains a machine token
const res = await fetch('https://api.yourapp.com/secure-data', {
headers: { Authorization: `Bearer ${token}` },
});
console.log(await res.json());
}
callProtectedApi();
The core token endpoint implementation is documented in packages/core/README.md.
Managing Federated Tokens
When you enable social connectors, Logto can persist provider tokens (Google, GitHub, etc.) in its Secret Vault. Retrieve these tokens via the secret-vault API to make authenticated calls to third-party services on behalf of the user. Configure this option in the connector settings within the Logto Console.
Summary
- Logto Architecture: Consists of the Core server (
packages/core/README.md), Connectors (packages/connectors/), and SDKs (packages/console/README.md). - Deployment: Run via Docker Compose, Logto Cloud, or GitPod using commands from the root
README.md. - Configuration: Create an application in the Logto Console to get your Client ID, then optionally configure social connectors like Google.
- SDK Integration: Use framework-specific packages (
@logto/react,@logto/nextjs,@logto/node) to initialize the provider and handle redirects. - Token Usage: Retrieve access tokens via
getAccessToken()oruseLogto()hooks to secure API routes and external service calls.
Frequently Asked Questions
What authentication protocols does Logto support?
Logto implements OpenID Connect (OIDC), OAuth 2.1, and SAML according to the architecture described in packages/core/README.md. This allows integration with a wide range of identity providers and enterprise systems.
Do I need to host my own Logto instance?
No. While you can self-host using Docker Compose (instructions in the root README.md), Logto also offers a managed Logto Cloud service. Both options provide the same API surface and Console interface.
How do I add social login providers like Google?
Add a connector from packages/connectors/. For Google specifically, follow the setup guide in packages/connectors/connector-google/README.md to configure the OAuth client ID and secret. The connector micro-service will handle the token exchange with Google’s servers.
Can I use Logto for machine-to-machine authentication?
Yes. Logto supports the Client Credentials flow for server-to-server authentication. Use the @logto/node SDK to create a client with your machine-to-machine credentials and call getAccessToken() to obtain bearer tokens for API access, as implemented in packages/toolkit.
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 →