Skip to content

React SDK

@seamless-auth/react is the official React integration for Seamless Auth.

It gives your app an auth provider, optional built-in auth screens, and a headless client for building custom sign-in and account-management UI.


Core exports:

  • AuthProvider
  • useAuth()
  • AuthRoutes, from the @seamless-auth/react/routes subpath
  • createSeamlessAuthClient()
  • useAuthClient()
  • usePasskeySupport()
  • hasScopedRole() and roleGrantsAccess()
  • WebAuthn PRF helpers such as encodePrfSalt() and isPasskeyPrfSupported()

Important exported types include AuthContextType, User, Credential, Organization, OAuthProvider, StepUpStatus, and the headless client input/result types.

The framework-free parts (the headless client, the session store, the ports and the transport) live in @seamless-auth/client, which @seamless-auth/react and @seamless-auth/react-native both build on and re-export. A React app never needs to install it directly.

Terminal window
npm install @seamless-auth/react

react-router-dom is an optional peer dependency. Install it only if you render the built-in screens from @seamless-auth/react/routes. AuthProvider, the hooks, and the headless client do not need it.


Style Use it when
AuthProvider + useAuth() You want app-wide auth state and high-level actions
createSeamlessAuthClient() You want fully custom auth screens outside React context
useAuthClient() You want custom React screens while reusing the provider apiHost
AuthRoutes (/routes) You want the built-in login, OTP, magic-link, and passkey screens

Most apps still wrap the route tree in AuthProvider. For a Next.js App Router application, see Next.js.


import { AuthProvider } from '@seamless-auth/react'
export function Root() {
return (
<AuthProvider apiHost="http://localhost:3000">
<App />
</AuthProvider>
)
}

AuthProvider does not create a router. If you use the built-in screens, it goes inside your <BrowserRouter>.

AuthProvider accepts:

Prop Purpose
apiHost Auth base URL (required)
autoDetectPreviousSignin Optional localStorage-backed returning-user hint
magicLinkRedirectUri Where magic links sent by the built-in screens land
initialSession A session the server already resolved, so the first paint is not a loading state (Next.js)
transport How the session travels: cookie (the default, for browsers) or bearer (for native)
ports Platform ports for passkeys and the OAuth redirect; browsers use the defaults

There is no service token, client id, or app id prop. The browser SDK carries no secret and relies on cookies. apiHost may be given with or without a trailing slash; the SDK sends requests to ${apiHost}/auth/....

apiHost is always your backend’s origin, the server where you mounted a Seamless Auth adapter (@seamless-auth/express, @seamless-auth/fastify, or @seamless-auth/nextjs) at /auth. It is never the auth API itself, on either path:

Path Set apiHost to Your backend forwards to
Managed Your backend, for example https://api.example.com The Auth Server URL copied from the portal
Self-hosted Your backend, for example http://localhost:3000 Your private seamless-auth-api

The Auth Server URL from the portal’s Auth API Configuration card goes in your backend’s AUTH_SERVER_URL, not in apiHost. The adapter holds the auth API’s tokens in signed cookies on your domain, so the browser never talks to the auth server directly. See the Managed Quickstart. The localhost example below is a local setup.


import { useAuth } from '@seamless-auth/react'
function Dashboard() {
const { user, isAuthenticated, hasScopedRole, logout } = useAuth()
if (!isAuthenticated) return <div>Not signed in</div>
return (
<div>
<p>{user?.email}</p>
{hasScopedRole('admin:read') && <a href="/admin">Admin</a>}
<button onClick={() => void logout()}>Log out</button>
</div>
)
}

The provider state includes user, credentials, organizations, activeOrganization, stepUpStatus, isAuthenticated, and loading.

Provider helpers include session refresh, logout, credential management, organization switching, OAuth start/callback helpers, passkey login, and step-up verification.


AuthRoutes ships from its own entry, so applications that build their own screens never load react-router:

import { AuthRoutes } from '@seamless-auth/react/routes'
import { Route, Routes } from 'react-router-dom'
function AppRoutes() {
const { isAuthenticated } = useAuth()
return (
<Routes>
<Route path="*" element={isAuthenticated ? <Dashboard /> : <AuthRoutes />} />
</Routes>
)
}

It serves these paths:

  • /login
  • /passkey-login
  • /verify-phone-otp
  • /verify-email-otp
  • /verify-magiclink
  • /oauth/callback
  • /register-passkey
  • /magic-link-sent

/verify-magiclink and /oauth/callback keep their names because the auth API builds magic links to the first and OAuth providers redirect to the second. The other paths were renamed from mixed case (/passKeyLogin, /verifyPhoneOTP, /verifyEmailOTP, /registerPasskey, /magiclinks-sent), which are no longer served.

The sign-in view registers with just an email (a phone is optional): submit an email, verify the emailed code, and you are signed in. It also renders a button for each configured OAuth provider and completes the flow at the built-in /oauth/callback route, so OAuth needs no extra UI wiring when you use AuthRoutes.

The built-in routes are optional wrappers over the same primitives exposed by useAuth() and the headless client. Your app still owns route protection and redirects.


Use createSeamlessAuthClient() when you want your own UI flow.

import { createSeamlessAuthClient } from '@seamless-auth/react'
const authClient = createSeamlessAuthClient({
apiHost: 'http://localhost:3000',
})
const { data, error } = await authClient.login({
identifier: 'user@example.com',
passkeyAvailable: true,
})

Every request method, on the client and on useAuth(), resolves to a SeamlessAuthResult<T>. It is a plain object with two fields, and exactly one of them is set:

Outcome data error
Success The response body, of type T null
Failure null A SeamlessAuthError with message, status, and body

const { data, error } = await ... uses destructuring to pull both fields out of the result object. It is the same as const result = await ... followed by reading result.data and result.error. Check error first, then read data:

const { data, error } = await authClient.listOAuthProviders()
if (error) {
setMessage(error.message)
return
}
setProviders(data.providers)

After the if (error) branch returns, TypeScript knows data is set. When you only need to know whether a call worked, take just the error: const { error } = await authClient.requestMagicLink().

Methods do not throw for HTTP or network failures, so a try/catch does not detect a failed call. A result has no .ok, .json(), or .success. Two methods do not return a result: isPasskeyPrfSupported() is a local capability check that returns a boolean, and authorizedFetch returns the raw Response from your own API.

The headless client covers:

  • current-user/session lookup
  • login and passkey login
  • registration
  • phone and email OTP
  • magic-link request, polling, and verification
  • OAuth provider listing, start, and callback completion
  • passkey registration
  • step-up status and verification
  • authenticator-app (TOTP) status, enrollment, and disable: getTotpStatus(), startTotpEnrollment(), verifyTotpEnrollment(code), disableTotp(code)
  • TOTP step-up: verifyStepUpWithTotp(code)
  • logout, signing out every session (logoutAllSessions()), and user deletion
  • credential update and deletion
  • organization and organization-member operations

The client reaches its platform through two ports, and AuthProvider takes them as an optional ports prop:

  • passkeys runs the WebAuthn ceremonies. The default is the browser’s WebAuthn API through SimpleWebAuthn.
  • oauthRedirect opens the provider. The default is a full-page navigation.

The defaults are what every earlier version did; a React app only reaches for the prop to swap a port out in tests. The same ports are what @seamless-auth/react-native fills with the native APIs.

transport chooses how the session travels: cookie, the default and the only one a browser should use, or bearer, where the client holds the auth API’s tokens through a tokenStorage port and speaks the adapter’s bearer contract. Leave it alone on the web.

useAuthorizedFetch() (or client.authorizedFetch) is a fetch for your own API that carries the session the way the transport does: credentials: 'include' on the web, the access token with one refresh-and-retry on native. A path resolves on apiHost:

const authorizedFetch = useAuthorizedFetch()
const plan = await authorizedFetch('/api/plan/mine').then(r => r.json())

Since @seamless-auth/client 0.5.0 (@seamless-auth/react 0.16.0), it sends the session only to apiHost and the origins you list in transport.trustedOrigins. A URL on any other origin rejects with UntrustedOriginError before anything is sent, and so does a relative URL that does not start with /. If your API is served from another origin of your own, list it. Each entry must be a bare https origin (http only on localhost):

<AuthProvider
apiHost="https://auth.example.com"
transport={{ trustedOrigins: ['https://api.example.com'] }}
>

For any other origin, use plain fetch.


For custom React screens, combine useAuth(), useAuthClient(), and usePasskeySupport().

Signing in takes two steps. login() only starts sign-in: it returns the loginMethods the account can use, and no session exists yet. The chosen method then completes sign-in, and only after it succeeds is there a session to refresh.

import { useState } from 'react'
import { useAuth, useAuthClient, usePasskeySupport } from '@seamless-auth/react'
function CustomLogin({ identifier }: { identifier: string }) {
const { refreshSession } = useAuth()
const authClient = useAuthClient()
const { passkeySupported, loading } = usePasskeySupport()
const [message, setMessage] = useState('')
async function signIn() {
const { data, error } = await authClient.login({
identifier,
passkeyAvailable: passkeySupported,
})
if (error) {
setMessage(error.message)
return
}
if (passkeySupported && data.loginMethods?.includes('passkey')) {
const { error: passkeyError } = await authClient.loginWithPasskey()
if (!passkeyError) {
await refreshSession()
return
}
}
const { error: otpError } = await authClient.requestLoginEmailOtp()
setMessage(otpError ? otpError.message : 'Check your email for a sign-in code.')
}
return (
<>
<button disabled={loading} onClick={() => void signIn()}>
Sign in
</button>
{message && <p>{message}</p>}
</>
)
}

The code screen finishes the fallback with verifyLoginEmailOtp(code) and calls refreshSession() once that call returns no error. useAuth().handlePasskeyLogin() runs loginWithPasskey() and refreshes the session for you. See How To Build Your Own Auth UI for the full screen, including magic-link and phone fallbacks.

Use refreshSession() after completing any custom flow that should update provider state.


OAuth starts in the frontend, but provider secrets and callback policy belong on the auth API.

import { useEffect, useState } from 'react'
import { useAuth, type OAuthProvider } from '@seamless-auth/react'
function OAuthButtons() {
const { listOAuthProviders, startOAuthLogin } = useAuth()
const [providers, setProviders] = useState<OAuthProvider[]>([])
useEffect(() => {
void listOAuthProviders().then(({ data }) => setProviders(data?.providers ?? []))
}, [listOAuthProviders])
async function signIn(providerId: string) {
const { data, error } = await startOAuthLogin({
providerId,
redirectUri: `${window.location.origin}/oauth/callback`,
returnTo: `${window.location.origin}/dashboard`,
})
if (!error) window.location.assign(data.authorizationUrl)
}
return providers.map((provider) => (
<button key={provider.id} onClick={() => void signIn(provider.id)}>
Continue with {provider.name}
</button>
))
}

Complete the callback by passing the provider code and Seamless Auth state back to the SDK:

const { finishOAuthLogin } = useAuth()
const params = new URLSearchParams(window.location.search)
const { error } = await finishOAuthLogin({
providerId: 'google',
code: params.get('code')!,
state: params.get('state')!,
})
if (error) {
setMessage(error.message)
return
}
navigate('/dashboard')

finishOAuthLogin does not throw when the callback fails, so check error before sending the user into the app.

OAuth requires LOGIN_METHODS to include oauth and at least one configured OAuth provider on the auth API.


useAuth() exposes organizations, activeOrganization, and switchOrganization().

For full custom organization management, use the headless client methods:

  • listOrganizations()
  • createOrganization(input)
  • getOrganization(organizationId)
  • updateOrganization(organizationId, input)
  • switchOrganization(organizationId)
  • listOrganizationMembers(organizationId)
  • addOrganizationMember(organizationId, input) (needs admin:write from API v0.19.4)
  • updateOrganizationMember(organizationId, userId, input)
  • removeOrganizationMember(organizationId, userId)

Switching organizations refreshes provider state so the active organization in useAuth() stays in sync with the session.


hasRole(role) is an exact role check. Use hasScopedRole(required) for scoped authorization.

const { hasRole, hasScopedRole } = useAuth()
hasRole('admin') // exact legacy check
hasScopedRole('admin:read') // true for admin, admin:read, or admin:write
hasScopedRole('admin:write') // true for admin or admin:write

The package also exports standalone hasScopedRole(roles, required) and roleGrantsAccess(...) helpers for code outside React context.


Use step-up auth when a signed-in user needs fresh verification before a sensitive action.

import { useAuth } from '@seamless-auth/react'
function SensitiveActionButton() {
const { refreshStepUpStatus, verifyStepUpWithPasskey } = useAuth()
async function runSensitiveAction() {
const status = await refreshStepUpStatus()
const verified = status.data?.fresh || !(await verifyStepUpWithPasskey()).error
if (!verified) return
await performSensitiveAction()
}
return <button onClick={() => void runSensitiveAction()}>Continue</button>
}

useAuth() also exposes verifyStepUpWithTotp(code) for users who have enrolled an authenticator app. See How To Use TOTP And Step-Up.


WebAuthn PRF lets compatible passkeys derive browser-local key material during a passkey assertion. Seamless Auth verifies the assertion, while PRF output stays in the browser caller.

const supported = await authClient.isPasskeyPrfSupported()
if (supported) {
await authClient.registerPasskey({
metadata: {
friendlyName: 'My laptop',
platform: 'macOS',
browser: 'Chrome',
deviceInfo: navigator.userAgent,
},
requestPrf: true,
})
}

For local key-unlock flows, request PRF during step-up:

const { data, error } = await authClient.verifyStepUpWithPasskeyPrf({
salt: vaultSaltBase64url,
credentialId,
})
if (!error) {
const keyMaterial = data.prf.output
}

Do not log PRF salts or output. Do not send PRF output to Seamless Auth.


The React SDK is not a backend and does not replace authorization enforcement.

The intended shape is:

React app
-> your backend API with /auth adapter routes
-> Seamless Auth API

The backend layer owns cookie validation, role enforcement, and service-to-service auth. In a Next.js application that backend is the application itself, through @seamless-auth/nextjs; see Next.js.