Examples
Practical examples for common authentication scenarios using Optare ID.
Protected API Route (Next.js)
Secure your API endpoints using token verification.
// app/api/protected/route.ts
import { createRemoteJWKSet, jwtVerify } from 'jose';
import { NextRequest, NextResponse } from 'next/server';
const JWKS = createRemoteJWKSet(
new URL('https://id.optare.one/.well-known/jwks.json')
);
export async function GET(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (!authHeader?.startsWith('Bearer ')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const { payload } = await jwtVerify(authHeader.slice(7), JWKS, {
issuer: 'https://id.optare.one',
});
const data = await fetchUserData(payload.sub);
return NextResponse.json(data);
} catch {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
}
}React Login Button
Use the Optare React SDK for authentication.
import { useOptare, SignInButton } from '@optare/optareid-react';
function LoginPage() {
const { isAuthenticated, user, logout } = useOptare();
if (isAuthenticated) {
return (
<div>
<p>Welcome, {user?.name}</p>
<button onClick={() => logout()}>Sign Out</button>
</div>
);
}
return <SignInButton label="Sign in with Optare" />;
}Protected Route Component
Require authentication for specific routes.
import { ProtectedRoute, useOptare } from '@optare/optareid-react';
function Dashboard() {
const { user } = useOptare();
return (
<ProtectedRoute>
<h1>Welcome, {user?.name}</h1>
<p>Your email: {user?.email}</p>
</ProtectedRoute>
);
}Role-Based UI
Show/hide UI based on user role.
import { useOptare } from '@optare/optareid-react';
function AdminPanel() {
const { user } = useOptare();
// Check role from the session/token claims
if (!['owner', 'admin'].includes(user?.role)) {
return null;
}
return (
<div>
<h2>Admin Panel</h2>
{/* Admin-only content */}
</div>
);
}Session Token for API Calls
Get access token for backend API calls.
import { useOptare } from '@optare/optareid-react';
function useApiClient() {
const { getAccessTokenSilently } = useOptare();
async function fetchProtectedData(endpoint: string) {
const token = await getAccessTokenSilently();
const response = await fetch(endpoint, {
headers: {
'Authorization': `Bearer ${token}`
}
});
return response.json();
}
return { fetchProtectedData };
}Next Steps
- Quick Start - Get started guide
- Token Verification - Backend verification
- Installation - Install SDK packages