Guida rapida: Next.js
Aggiungi l’accesso a un’app Next.js con l’App Router. L’SDK @usher/nextjs è in arrivo; finché non sarà disponibile, questa guida usa il flusso standard di OpenID Connect, che è esattamente ciò che l’SDK farà al posto tuo.
Prima di iniziare
- Un’app Next.js 15 o 16 che usa l’App Router.
- Un ambiente Usher. In Usher Console, apri il tuo progetto, scegli un ambiente e prendi nota del suo issuer.
Registra la tua app
In Console, vai su Applicazioni e crea un’app web. Aggiungi esattamente questo URI di reindirizzamento:
http://localhost:3000/auth/callbackCopia il client ID e il client secret. Il secret viene mostrato una sola volta.
Aggiungi le variabili d’ambiente
USHER_ISSUER=https://acme.usherid.com
USHER_CLIENT_ID=your_client_id
USHER_CLIENT_SECRET=your_client_secret
APP_URL=http://localhost:3000Installa un client OpenID Connect
Funziona qualsiasi client certificato. Questa guida usa openid-client, che gestisce discovery, PKCE e convalida dei token.
pnpm add openid-clientEsegui la discovery del tuo issuer
La discovery legge una sola volta gli endpoint e le chiavi dell’issuer, così non c’è nulla di scritto a mano nel codice.
import * as client from 'openid-client'
let config: Promise<client.Configuration> | undefined
export function usher() {
config ??= client.discovery(
new URL(process.env.USHER_ISSUER!),
process.env.USHER_CLIENT_ID!,
process.env.USHER_CLIENT_SECRET!,
)
return config
}
export const redirectUri = `${process.env.APP_URL}/auth/callback`Manda le persone alla Lobby
Un route handler genera un verifier PKCE e un valore state, li conserva in un cookie di breve durata e reindirizza alla Lobby.
import * as client from 'openid-client'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { redirectUri, usher } from '@/lib/usher'
export async function GET() {
const config = await usher()
const codeVerifier = client.randomPKCECodeVerifier()
const state = client.randomState()
const jar = await cookies()
jar.set('usher_flow', JSON.stringify({ codeVerifier, state }), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/auth',
maxAge: 600,
})
const url = client.buildAuthorizationUrl(config, {
redirect_uri: redirectUri,
scope: 'openid profile email offline_access',
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
code_challenge_method: 'S256',
state,
})
redirect(url.href)
}Gestisci il callback
Usher rimanda indietro la persona con un codice. Scambialo con i token; openid-client verifica al posto tuo lo state, il verifier PKCE e la firma del token ID.
import * as client from 'openid-client'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { usher } from '@/lib/usher'
export async function GET(request: Request) {
const config = await usher()
const jar = await cookies()
const flow = JSON.parse(jar.get('usher_flow')?.value ?? '{}')
jar.delete('usher_flow')
const tokens = await client.authorizationCodeGrant(config, new URL(request.url), {
pkceCodeVerifier: flow.codeVerifier,
expectedState: flow.state,
})
const claims = tokens.claims()! // sub, email, name, …
// start your own session here: store claims.sub, and keep the refresh token server-side
redirect('/')
}Esci
Chiudi la sessione della persona nella tua app, poi mandala all’endpoint di fine sessione di Usher, così anche la Lobby la dimentica.
import * as client from 'openid-client'
import { redirect } from 'next/navigation'
import { usher } from '@/lib/usher'
export async function GET() {
const config = await usher()
// clear your own session first
const url = client.buildEndSessionUrl(config, {
post_logout_redirect_uri: process.env.APP_URL!,
})
redirect(url.href)
}Con l’SDK
Quando @usher/nextjs sarà pubblicato, la stessa app avrà questo aspetto. L’anteprima qui sotto potrebbe cambiare prima del rilascio.
// app/layout.tsx
import { UsherProvider } from '@usher/nextjs'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<UsherProvider>{children}</UsherProvider>
</body>
</html>
)
}
// app/page.tsx
import { SignIn, UserButton, currentUser } from '@usher/nextjs'
export default async function Page() {
const user = await currentUser()
return user ? <UserButton /> : <SignIn />
}