Enable guest mode to support unauthenticated users with fingerprinting
Guest mode allows your application to work with both authenticated and unauthenticated users, providing a seamless experience with built-in fingerprint-based guest IDs.
function ProtectedPage() { const { user } = useAuth({ middleware: 'auth', redirectTo: '/login', // Redirect if not authenticated }) if (!user) return null // or loading indicator return <div>Protected content for {user.name}</div>}
When guest mode is enabled, the auth context includes additional fields:
interface AuthContext { userId: string | null // User ID from token (null for guests) isAuthenticated: boolean // true for authenticated users isGuest: boolean // true for guest users payload: AuthPayload | null // Full JWT payload (null for guests) guestId?: string // Guest fingerprint ID (when allowGuest is true)}
When a user visits your site without authentication, logto-authkit automatically generates a unique guest ID using browser fingerprinting.
2
Persistence
The guest ID is stored in the browser’s guest_logto_authtoken cookie, ensuring the same ID is used across sessions.
3
Server Verification
When allowGuest: true is set, the server helpers can return a guest auth context when no valid JWT token is available, using the guest cookie to persist the guest ID.
4
Upgrade to Authenticated
When a guest user signs in, they receive a proper JWT token. You can associate their previous guest activity with their authenticated account using the guest ID.
import { useAuth } from '@ouim/logto-authkit'import { useEffect, useState } from 'react'function ProductPage() { const { user, isLoadingUser } = useAuth({ middleware: 'guest' }) const [guestId, setGuestId] = useState<string | null>(null) useEffect(() => { // Store guest ID before user signs in if (!user && typeof window !== 'undefined') { const storedGuestId = document.cookie .split('; ') .find((entry) => entry.startsWith('guest_logto_authtoken=')) ?.split('=')[1] ?? null setGuestId(storedGuestId) } }, [user]) useEffect(() => { // User just signed in - migrate guest data if (user && guestId) { migrateGuestData(guestId, user.id) setGuestId(null) } }, [user, guestId]) async function migrateGuestData(guestId: string, userId: string) { // Call your API to associate guest data with the user await fetch('/api/migrate-guest-data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ guestId, userId }), }) } if (isLoadingUser) return <div>Loading...</div> return ( <div> {user ? ( <p>Welcome back, {user.name}!</p> ) : ( <p>Browsing as guest (ID: {guestId})</p> )} </div> )}
Guest IDs are stored in a browser cookie and can still be cleared by the user. Don’t rely on them for critical functionality or security. They’re best used for convenience features like cart persistence.