オーラベースのロゴ
オーラベースドキュメント
ドキュメント›ガイド›Next.js sign-in pages

Next.js の既製のサインイン ページ

8 つの小さなファイルにより、Aurabase メール内のリンクが指すページを含む、Next.js アプリに完全なサインイン フローが提供されます。

8 分 読み取り·レベル 中間·2026/10/25 に改訂
この英語のテキストはフランス語のオリジナルから自動的に生成されたもので、まだレビューされていません。
この翻訳以降、英語のソースが変更されました。一部の情報は古い可能性があります。
このページは自動翻訳されました。英語版が正式です。
#
セットアップ

1. クライアントとプロキシ

これらのページでは、Cookie セッションで App Router を使用します (Next.js SSRを参照)。 NEXT_PUBLIC_AURABASE_URL および NEXT_PUBLIC_AURABASE_ANON_KEYを設定し、サーバー クライアントとプロキシを追加します。 Next.js 15 では、ファイルに middleware.ts 、関数に middlewareという名前を付けます。

lib/aurabase/server.tstypescript
import { cookies } from 'next/headers'
import { createServerClient } from '@aurabase/aurabase-js/ssr'

export async function serverClient() {
  const store = await cookies()
  return createServerClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, {
    cookies: {
      getAll: () => store.getAll(),
      // サーバー コンポーネントは Cookie を書き込むことができません。代わりに、以下のプロキシがセッションを更新します。
      setAll(list) {
        try {
          list.forEach(({ name, value, options }) => store.set(name, value, options))
        } catch {}
      },
    },
  })
}
proxy.tstypescript
import { NextResponse, type NextRequest } from 'next/server'
import { createServerClient } from '@aurabase/aurabase-js/ssr'

const PROTECTED = ['/dashboard']

export async function proxy(request: NextRequest) {
  const response = NextResponse.next({ request })
  const aura = createServerClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, {
    cookies: {
      getAll: () => request.cookies.getAll(),
      setAll(list) {
        list.forEach(({ name, value, options }) => {
          request.cookies.set(name, value)
          response.cookies.set(name, value, options)
        })
      },
    },
  })
  // getUser() はトークンを更新し、サーバーにユーザーが誰であるかを尋ねます。 getSession() を使用して承認しないでください。
  const { data: user } = await aura.auth.getUser()
  if (!user && PROTECTED.some((p) => request.nextUrl.pathname.startsWith(p))) {
    return NextResponse.redirect(new URL('/login', request.url))
  }
  return response
}

export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }
#
サインイン

2. サインインしてサインアップする

app/login/actions.tstypescript
'use server'
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'

export async function login(formData: FormData) {
  const aura = await serverClient()
  const { data, error } = await aura.auth.signInWithPassword({
    email: String(formData.get('email')),
    password: String(formData.get('password')),
  })
  if (error) redirect(`/login?error=${encodeURIComponent(error.code ?? 'ERROR')}`)
  // MFA が有効になっているユーザーは、セッションではなくチャレンジを取得します。ここでコードを問い合わせてください。
  if (data && 'mfa_required' in data) redirect(`/login?error=MFA_REQUIRED`)
  redirect('/dashboard')
}

export async function sendMagicLink(formData: FormData) {
  const aura = await serverClient()
  await aura.auth.signInWithMagicLink({ email: String(formData.get('email')) })
  redirect('/login?sent=1')
}
app/login/page.tsxtsx
import Link from 'next/link'
import { login, sendMagicLink } from './actions'

export default async function LoginPage({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
  const { error, sent } = await searchParams
  return (
    <main>
      <h1>Sign in</h1>
      {error && <p role="alert">Sign-in failed: {error}</p>}
      {sent && <p>If this address has an account, a sign-in link was sent.</p>}
      <form action={login}>
        <input name="email" type="email" placeholder="Email" required />
        <input name="password" type="password" placeholder="Password" required />
        <button type="submit">Sign in</button>
      </form>
      <form action={sendMagicLink}>
        <input name="email" type="email" placeholder="Email" required />
        <button type="submit">Email me a sign-in link</button>
      </form>
      <p>
        <Link href="/signup">Create an account</Link> · <Link href="/forgot-password">Forgot your password?</Link>
      </p>
    </main>
  )
}
app/signup/actions.tstypescript
'use server'
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'

export async function signup(formData: FormData) {
  const aura = await serverClient()
  const { data, error } = await aura.auth.signUp({
    email: String(formData.get('email')),
    password: String(formData.get('password')),
  })
  if (error) redirect(`/signup?error=${encodeURIComponent(error.message)}`)
  // プロジェクトで電子メールによる確認が必要なときは、まだセッションがありません。`data.session` は null です。
  redirect(data?.session ? '/dashboard' : '/signup?check=1')
}
app/signup/page.tsxtsx
import Link from 'next/link'
import { signup } from './actions'

export default async function SignupPage({ searchParams }: { searchParams: Promise<{ error?: string; check?: string }> }) {
  const { error, check } = await searchParams
  return (
    <main>
      <h1>Create an account</h1>
      {error && <p role="alert">{error}</p>}
      {check && <p>Check your inbox: confirm your email address to finish.</p>}
      <form action={signup}>
        <input name="email" type="email" placeholder="Email" required />
        <input name="password" type="password" placeholder="Password" required minLength={8} />
        <button type="submit">Sign up</button>
      </form>
      <p>
        <Link href="/login">Already have an account?</Link>
      </p>
    </main>
  )
}
#
リセット

3. パスワードのリセット

リセット電子メールは <Site URL>/reset-password?token=…へのリンクです。 Studio › Authentication › Configuration でサイト URL を設定します。

app/forgot-password/actions.tstypescript
'use server'
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'

export async function requestReset(formData: FormData) {
  const aura = await serverClient()
  await aura.auth.resetPasswordForEmail(String(formData.get('email')))
  // アドレスにアカウントがあるかどうかに関係なく、同じ答えになります (アカウントの列挙はありません)。
  redirect('/forgot-password?sent=1')
}
app/forgot-password/page.tsxtsx
import { requestReset } from './actions'

export default async function ForgotPasswordPage({ searchParams }: { searchParams: Promise<{ sent?: string }> }) {
  const { sent } = await searchParams
  return (
    <main>
      <h1>Reset your password</h1>
      {sent && <p>If this address has an account, a reset link was sent.</p>}
      <form action={requestReset}>
        <input name="email" type="email" placeholder="Email" required />
        <button type="submit">Send the link</button>
      </form>
    </main>
  )
}
app/reset-password/actions.tstypescript
'use server'
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'

export async function resetPassword(formData: FormData) {
  const token = String(formData.get('token'))
  const aura = await serverClient()
  const { error } = await aura.auth.resetPassword(token, String(formData.get('password')))
  if (error) redirect(`/reset-password?token=${encodeURIComponent(token)}&error=${encodeURIComponent(error.message)}`)
  // リセットすると、ユーザーは新しいセッションでサインインします。古いセッションは取り消されました。
  redirect('/dashboard')
}
app/reset-password/page.tsxtsx
import { resetPassword } from './actions'

export default async function ResetPasswordPage({ searchParams }: { searchParams: Promise<{ token?: string; error?: string }> }) {
  const { token, error } = await searchParams
  if (!token) return <main><p role="alert">This link is incomplete. Request a new one.</p></main>
  return (
    <main>
      <h1>Choose a new password</h1>
      {error && <p role="alert">{error}</p>}
      <form action={resetPassword}>
        <input type="hidden" name="token" value={token} />
        <input name="password" type="password" placeholder="New password" required minLength={8} />
        <button type="submit">Save</button>
      </form>
    </main>
  )
}

確認メールとマジックリンクメールは <Site URL>/verify-email?token=… および <Site URL>/magic-link/verify?token=…にリンクします。ルート ハンドラーはトークンを消費し、リダイレクトします。

app/verify-email/route.tstypescript
import { NextResponse, type NextRequest } from 'next/server'
import { serverClient } from '@/lib/aurabase/server'

export async function GET(request: NextRequest) {
  const token = request.nextUrl.searchParams.get('token')
  if (token) {
    const aura = await serverClient()
    const { error } = await aura.auth.verifyOtp({ type: 'signup', token })
    if (!error) return NextResponse.redirect(new URL('/dashboard', request.url))
  }
  return NextResponse.redirect(new URL('/login?error=LINK_INVALID', request.url))
}
app/magic-link/verify/route.tstypescript
import { NextResponse, type NextRequest } from 'next/server'
import { serverClient } from '@/lib/aurabase/server'

export async function GET(request: NextRequest) {
  const token = request.nextUrl.searchParams.get('token')
  if (token) {
    const aura = await serverClient()
    const { error } = await aura.auth.verifyMagicLink(token)
    if (!error) return NextResponse.redirect(new URL('/dashboard', request.url))
  }
  return NextResponse.redirect(new URL('/login?error=LINK_INVALID', request.url))
}
#
ダッシュボード

5. 保護されたページ

app/dashboard/actions.tstypescript
'use server'
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'

export async function logout() {
  const aura = await serverClient()
  await aura.auth.signOut()
  redirect('/login')
}
app/dashboard/page.tsxtsx
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'
import { logout } from './actions'

export default async function DashboardPage() {
  const aura = await serverClient()
  const { data: user } = await aura.auth.getUser()
  if (!user) redirect('/login')
  return (
    <main>
      <h1>Dashboard</h1>
      <p>Signed in as {user.email}</p>
      <form action={logout}>
        <button type="submit">Sign out</button>
      </form>
    </main>
  )
}
#
テスト

6. ローカルで試してみる

ローカル スタックでは、電子メールは送信されるのではなく、Mailpit によってキャプチャされます。 kubectl -n aurabase-dev port-forward svc/aurabase-mailpit 8025:8025、次に http://localhost:8025で受信箱を開きます。アプリのオリジン (例: http://localhost:3000/*) を Studio › Authentication › Configuration › Redirect URLs に追加し、サイト URL をそれに設定します。

情報

proxy.ts は、 PROTECTEDにリストされているルートでのみリダイレクトします。プロキシはそれ自体が承認境界ではないため、ダッシュボード ページは getUser() を使用してユーザーを再度チェックします。