Next.js集成Google认证后重定向URL自动添加80端口问题解决
Next.js 14 + Supabase Google认证重定向80端口SSL错误解决方法
问题背景
部署在Netlify的Next.js 14应用,使用Supabase作为后端,Google认证成功后重定向URL被自动附加80端口(例如https://production-url.com:80/?code=randomcode),触发Chrome的ERR_SSL_PROTOCOL_ERROR安全连接错误。本地开发环境无此问题,手动将端口替换为443后认证流程可正常完成。
解决方案
1. 显式配置重定向地址,避免依赖location.origin
Netlify的反向代理环境中,location.origin可能被识别为HTTP协议,导致Supabase生成带80端口的重定向地址。直接通过环境变量指定生产环境的HTTPS地址:
修改认证逻辑中的handleGoogleAuthLogin函数:
const handleGoogleAuthLogin = async () => { // 从环境变量读取应用地址,避免动态获取的origin带错误端口 const redirectUrl = `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`; const { data, error } = await supabase.auth.signInWithOAuth({ provider: "google", options: { redirectTo: redirectUrl, }, }); };
在Netlify控制台的环境变量中添加NEXT_PUBLIC_APP_URL,值为https://production-url.com。
2. 更新Supabase后台重定向URL配置
确保Supabase后台的重定向URL仅包含正确的HTTPS路径,将https://production-url.com/修改为https://production-url.com/**,覆盖所有子路径,避免路径匹配不完整的问题。
3. 强制Netlify传递正确的协议头
在next.config.js中添加配置,让Next.js识别Netlify的反向代理协议头:
/** @type {import('next').NextConfig} */ const nextConfig = { async headers() { return [ { source: '/:path*', headers: [ { key: 'X-Forwarded-Proto', value: 'https', }, ], }, ]; }, }; module.exports = nextConfig;
或者在项目根目录的netlify.toml中添加:
[[headers]] for = "/*" [headers.values] X-Forwarded-Proto = "https"
4. 修正回调页面的重定向逻辑
在auth/callback的GET处理函数中,手动构造正确的HTTPS地址,避免错误端口:
import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; import { cookies } from "next/headers"; import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs"; export async function GET(request: NextRequest) { const requestUrl = new URL(request.url); const code = requestUrl.searchParams.get("code"); if (code) { const supabase = createRouteHandlerClient({ cookies }); await supabase.auth.exchangeCodeForSession(code); // 构造正确的HTTPS origin,移除错误的80端口 const correctOrigin = requestUrl.origin.replace(":80", "").replace("http:", "https:"); return NextResponse.redirect(correctOrigin); } // 无code时重定向到首页 return NextResponse.redirect(new URL("/", requestUrl.origin.replace(":80", "").replace("http:", "https:"))); }
内容的提问来源于stack exchange,提问作者Alvin
相关产品推荐
相关产品推荐

