跳到内容
光环标志
光环基地

Next.js 的现成登录页面

八个小文件为 Next.js 应用程序提供了完整的登录流程,包括 Aurabase 电子邮件中的链接指向的页面。

教程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。

信息

Next.js 16 的 create-next-app 会启用 Cache Components:页面只能在 <Suspense> 下渲染的组件中读取 cookies() 或 searchParams,否则 next build 会以 « uncached or runtime data during prerendering » 终止。下面的页面就是这样编写的:页面本身是静态的,依赖请求的部分以流的方式到达。

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(),
      // Server Components cannot write cookies: the proxy below refreshes the session instead.
      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() refreshes the tokens AND asks the server who the user is. Never authorize with 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')}`)
  // A user with MFA enabled gets a challenge instead of a session: ask for the code here.
  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 { Suspense } from 'react'
import Link from 'next/link'
import { login, sendMagicLink } from './actions'

type Search = Promise<{ error?: string; sent?: string }>

// Reads the query string: must render under <Suspense> (Next.js 16 Cache Components).
async function Notices({ searchParams }: { searchParams: Search }) {
  const { error, sent } = await searchParams
  return (
    <>
      {error && <p role="alert">Sign-in failed: {error}</p>}
      {sent && <p>If this address has an account, a sign-in link was sent.</p>}
    </>
  )
}

export default function LoginPage({ searchParams }: { searchParams: Search }) {
  return (
    <main>
      <h1>Sign in</h1>
      <Suspense fallback={null}>
        <Notices searchParams={searchParams} />
      </Suspense>
      <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)}`)
  // When the project requires email confirmation there is no session yet: `data.session` is null.
  redirect(data?.session ? '/dashboard' : '/signup?check=1')
}
app/signup/page.tsxtsx
import { Suspense } from 'react'
import Link from 'next/link'
import { signup } from './actions'

type Search = Promise<{ error?: string; check?: string }>

async function Notices({ searchParams }: { searchParams: Search }) {
  const { error, check } = await searchParams
  return (
    <>
      {error && <p role="alert">{error}</p>}
      {check && <p>Check your inbox: confirm your email address to finish.</p>}
    </>
  )
}

export default function SignupPage({ searchParams }: { searchParams: Search }) {
  return (
    <main>
      <h1>Create an account</h1>
      <Suspense fallback={null}>
        <Notices searchParams={searchParams} />
      </Suspense>
      <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 › 身份验证 › 配置中设置站点 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')))
  // Same answer whether or not the address has an account (no account enumeration).
  redirect('/forgot-password?sent=1')
}
app/forgot-password/page.tsxtsx
import { Suspense } from 'react'
import { requestReset } from './actions'

type Search = Promise<{ sent?: string }>

async function Notice({ searchParams }: { searchParams: Search }) {
  const { sent } = await searchParams
  return sent ? <p>If this address has an account, a reset link was sent.</p> : null
}

export default function ForgotPasswordPage({ searchParams }: { searchParams: Search }) {
  return (
    <main>
      <h1>Reset your password</h1>
      <Suspense fallback={null}>
        <Notice searchParams={searchParams} />
      </Suspense>
      <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)}`)
  // The reset signs the user in with a new session; older sessions were revoked.
  redirect('/dashboard')
}
app/reset-password/page.tsxtsx
import { Suspense } from 'react'
import { resetPassword } from './actions'

type Search = Promise<{ token?: string; error?: string }>

async function ResetForm({ searchParams }: { searchParams: Search }) {
  const { token, error } = await searchParams
  if (!token) return <p role="alert">This link is incomplete. Request a new one.</p>
  return (
    <>
      <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>
    </>
  )
}

export default function ResetPasswordPage({ searchParams }: { searchParams: Search }) {
  return (
    <main>
      <Suspense fallback={null}>
        <ResetForm searchParams={searchParams} />
      </Suspense>
    </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 { Suspense } from 'react'
import { redirect } from 'next/navigation'
import { serverClient } from '@/lib/aurabase/server'
import { logout } from './actions'

// Reads the session cookie: must render under <Suspense> (Next.js 16 Cache Components).
async function Account() {
  const aura = await serverClient()
  const { data: user } = await aura.auth.getUser()
  if (!user) redirect('/login')
  return (
    <>
      <p>Signed in as {user.email}</p>
      <form action={logout}>
        <button type="submit">Sign out</button>
      </form>
    </>
  )
}

export default function DashboardPage() {
  return (
    <main>
      <h1>Dashboard</h1>
      <Suspense fallback={<p>Loading…</p>}>
        <Account />
      </Suspense>
    </main>
  )
}

6.本地尝试#

在本地栈中,邮件会被 Mailpit 捕获而不会真正发送,控制台的“请验证您的邮箱”界面会直接显示验证链接(开发模式)。对于您自己应用的邮件,请用 kubectl -n aurabase-dev port-forward svc/aurabase-mailpit 8025:8025 打开 Mailpit 收件箱,然后访问 http://localhost:8025。请把您应用的源(例如 http://localhost:3000/*)添加到 Studio › Authentication › Configuration › Redirect URLs,并将 Site URL 设为它。

信息

proxy.ts 仅在 PROTECTED中列出的路由上重定向;仪表板页面再次使用 getUser() 检查用户,因为代理本身并不是授权边界。