Inicio rápido: Next.js
Agrega el inicio de sesión a una app de Next.js con el App Router. El SDK @usher/nextjs está en camino; hasta que llegue, esta guía usa el flujo estándar de OpenID Connect, que es exactamente lo que el SDK hará por ti.
Antes de empezar
- Una app de Next.js 15 o 16 que use el App Router.
- Un entorno de Usher. En Usher Console, abre tu proyecto, elige un entorno y anota su emisor.
Registra tu app
En Console, ve a Aplicaciones y crea una app web. Agrega exactamente esta URI de redirección:
http://localhost:3000/auth/callbackCopia el ID de cliente y el secreto de cliente. El secreto se muestra una sola vez.
Agrega tus variables de entorno
USHER_ISSUER=https://acme.usherid.com
USHER_CLIENT_ID=your_client_id
USHER_CLIENT_SECRET=your_client_secret
APP_URL=http://localhost:3000Instala un cliente de OpenID Connect
Cualquier cliente certificado funciona. Esta guía usa openid-client, que se encarga del descubrimiento, de PKCE y de la validación de tokens.
pnpm add openid-clientDescubre tu emisor
El descubrimiento lee una sola vez los endpoints y las claves del emisor, así que no hay nada escrito a mano en el código.
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`Envía a las personas al Lobby
Un controlador de ruta crea un verificador PKCE y un valor de state, los guarda en una cookie de corta duración y redirige al 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)
}Gestiona el callback
Usher devuelve a la persona con un código. Cámbialo por tokens; openid-client comprueba por ti el state, el verificador PKCE y la firma del token de 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('/')
}Cierra la sesión
Termina la sesión de la persona en tu app y luego envíala al endpoint de cierre de sesión de Usher, para que el Lobby también la olvide.
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 el SDK
Cuando se publique @usher/nextjs, la misma app se verá así. Esta vista previa puede cambiar antes del lanzamiento.
// 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 />
}