İçeriğe geç
Belgeler · Next.js

Hızlı başlangıç: Next.js

App Router kullanan bir Next.js uygulamasına giriş ekleyin. @usher/nextjs SDK’sı yolda; o gelene kadar bu kılavuz standart OpenID Connect akışını kullanıyor. SDK da sizin için tam olarak bunu yapacak.

Başlamadan önce

  • App Router kullanan bir Next.js 15 ya da 16 uygulaması.
  • Bir Usher ortamı. Usher Console’da projenizi açın, bir ortam seçin ve yayıncısını not edin.

Uygulamanızı kaydedin

Console’da Uygulamalar bölümüne gidin ve bir Web uygulaması oluşturun. Şu yönlendirme URI’sini birebir ekleyin:

http://localhost:3000/auth/callback

İstemci kimliğini ve istemci gizli anahtarını kopyalayın. Gizli anahtar yalnızca bir kez gösterilir.

Ortam değişkenlerinizi ekleyin

.env.local
USHER_ISSUER=https://acme.usherid.com
USHER_CLIENT_ID=your_client_id
USHER_CLIENT_SECRET=your_client_secret
APP_URL=http://localhost:3000

Bir OpenID Connect istemcisi kurun

Sertifikalı her istemci çalışır. Bu kılavuz; keşfi, PKCE’yi ve belirteç doğrulamayı üstlenen openid-client kütüphanesini kullanıyor.

Terminal
pnpm add openid-client

Yayıncınızı keşfedin

Keşif, yayıncının uç noktalarını ve anahtarlarını bir kez okur; böylece hiçbir şeyi koda gömmeniz gerekmez.

lib/usher.ts
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`

İnsanları Lobby’ye gönderin

Bir route handler, bir PKCE doğrulayıcısı ve bir state değeri oluşturur, bunları kısa ömürlü bir çerezde tutar ve Lobby’ye yönlendirir.

app/auth/sign-in/route.ts
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)
}

Geri dönüşü karşılayın

Usher kişiyi bir kodla geri gönderir. Kodu belirteçlerle değiştirin; openid-client state değerini, PKCE doğrulayıcısını ve kimlik belirtecinin imzasını sizin için denetler.

app/auth/callback/route.ts
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('/')
}

Çıkış yapın

Kişinin uygulamanızdaki oturumunu sonlandırın, ardından Lobby’nin de onu unutması için kişiyi Usher’ın oturum sonlandırma uç noktasına gönderin.

app/auth/sign-out/route.ts
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)
}

SDK ile

@usher/nextjs yayımlandığında aynı uygulama böyle görünecek. Aşağıdaki önizleme, sürümden önce değişebilir.

app/layout.tsx · app/page.tsx (önizleme)
// 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 />
}

Sonraki adımlar