Next.js14/App Router中Supabase Auth OAuth登录后设置跳转URL(PKCE)
解决Supabase OAuth登录后重定向回来源页面的问题
1. 在登录页面传递来源页面的next参数
当用户从目标页面(如/cart)进入登录页时,需将当前页面路径作为next参数传递给登录页,再通过表单隐藏字段传递给服务端动作:
// /app/auth/login/page.jsx export default function LoginPage({ searchParams }) { const next = searchParams.next ?? '/'; return ( <form action={socialLogin}> {/* 隐藏字段传递next参数 */} <input type="hidden" name="next" value={next} /> {/* 登录提供商按钮 */} <button type="submit" name="provider" value="google">Google登录</button> <button type="submit" name="provider" value="github">GitHub登录</button> </form> ); }
如果是通过导航链接跳转登录,需在链接中拼接next参数:
<Link href={`/login?next=${encodeURIComponent(window.location.pathname)}`}>登录</Link>
2. 修改服务端登录动作,附加next到回调URL
在/app/auth/login/actions.js中,获取表单里的next参数,将其拼接到redirectTo的URL中,让Supabase回调时携带该参数:
"use server"; import { redirect } from "next/navigation"; import { createClient } from "@/utils/supabase/server"; export async function socialLogin(formData) { const provider = formData.get("provider"); const next = formData.get("next") ?? "/"; if (!provider) { return redirect(`/login?message=No provider selected&next=${encodeURIComponent(next)}`); } const supabase = await createClient(); // 拼接next参数到回调URL,生产环境建议用环境变量替代硬编码域名 const redirectTo = `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback?next=${encodeURIComponent(next)}`; const { data, error } = await supabase.auth.signInWithOAuth({ provider, options: { redirectTo }, }); if (error) { return redirect(`/login?message=Could not authenticate user&next=${encodeURIComponent(next)}`); } if (data.url) redirect(data.url); }
3. 确认回调页面的next参数处理逻辑
你的/app/auth/callback/route.js已经包含next参数的获取逻辑,无需额外修改:
const next = searchParams.get("next") ?? "/";
该逻辑会优先使用传递的next值,默认 fallback 到首页/,确保跳转逻辑正常。
4. 验证回调URL基础配置
确保Supabase控制台和OAuth提供商(如Google Cloud)的回调URL仅配置基础路径(如http://localhost:3000/auth/callback),不需要包含next参数,参数部分不会影响回调URL的匹配验证。
完成上述步骤后,用户从/cart等页面进入登录,认证完成后将自动重定向回原页面。
内容的提问来源于stack exchange,提问作者kiwaisako
相关产品推荐
相关产品推荐

