You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS & Supabase部署Render后认证路由重定向异常求助

解决Supabase登录重定向到localhost的问题

核心排查与修复步骤

1. 修正Supabase控制台的认证URL配置

  • 进入Supabase项目控制台,找到认证 > URL配置页面
  • 把站点URL改成生产环境地址:https://circulart-statistics.onrender.com
  • 在重定向URL列表里添加生产环境的回调地址,比如:
    • https://circulart-statistics.onrender.com/auth/callback
    • https://circulart-statistics.onrender.com/clients
  • 注意:本地开发的URL可以保留,但生产环境URL要确保优先级最高,或者通过环境区分配置

2. 配置render.com的环境变量

在render.com项目的环境变量面板中添加以下变量:

  • NEXT_PUBLIC_SUPABASE_URL: 你的Supabase项目官方URL
  • NEXT_PUBLIC_SUPABASE_ANON_KEY: 你的Supabase匿名密钥
  • NEXT_PUBLIC_SITE_URL: https://circulart-statistics.onrender.com
  • 删掉手动设置的PORT变量,render会自动分配端口,不需要指定localhost相关值

3. 修复middleware.ts中的站点URL初始化

在middleware.ts里,初始化Supabase客户端时,必须用环境变量或请求来源URL,不能硬编码localhost。示例代码:

import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
  const res = NextResponse.next()
  const supabase = createMiddlewareClient({ req, res })
  
  // 用环境变量或请求来源URL获取站点地址,禁止硬编码
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || req.nextUrl.origin
  
  // 其他业务逻辑...
  
  return res
}

4. 调整sign-in路由的重定向逻辑

确保sign-in路由里的重定向目标使用生产环境地址,示例:

// app/auth/sign-in/route.ts
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  const requestUrl = new URL(request.url)
  const code = requestUrl.searchParams.get('code')

  if (code) {
    const supabase = createRouteHandlerClient({ cookies })
    await supabase.auth.exchangeCodeForSession(code)
  }

  // 重定向到生产环境的clients页面,用环境变量或请求来源URL
  return NextResponse.redirect(new URL('/clients', process.env.NEXT_PUBLIC_SITE_URL || requestUrl.origin))
}

5. 验证render.com服务器配置

  • 确认项目的构建命令是npm run build,启动命令是npm start,render会自动处理端口映射
  • 查看服务器日志,确认环境变量是否正确加载,没有输出localhost相关的错误信息

额外调试技巧

  • 在middleware里打印req.nextUrl.origin和process.env.NEXT_PUBLIC_SITE_URL的值,确认生产环境中是否正确获取到https://circulart-statistics.onrender.com
  • 查看Supabase的认证日志,检查重定向请求的来源和目标URL是否符合预期

内容的提问来源于stack exchange,提问作者Carlos del Río Francés

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 12:34:59