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

在Next.js中为Supabase Auth配置环境专属重定向URL

解决Next.js + Supabase 环境差异化重定向URL问题

核心方案:通过环境变量动态传递redirect_to参数

Supabase的各类认证方法(如signInWithOAuth、signInWithPassword等)支持传入redirect_to参数,用来覆盖控制台设置的默认Site URL。结合Next.js的环境变量,就能在本地和生产环境分别指定不同的重定向地址。

1. 配置环境变量

在项目根目录创建两个环境变量文件:

  • 本地开发:.env.local
    NEXT_PUBLIC_SUPABASE_REDIRECT_URL=http://localhost:3000
    
  • 生产环境:.env.production
    NEXT_PUBLIC_SUPABASE_REDIRECT_URL=https://some-production-url.com
    

注意:变量名必须以NEXT_PUBLIC_开头,才能在客户端代码中正常访问。

2. 在认证函数中动态传入redirect_to

无论使用客户端组件还是服务器组件调用Supabase认证,都可以直接读取环境变量并传入参数:

客户端组件示例

import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';

export default function LoginButton() {
  const supabase = createClientComponentClient();

  const handleOAuthLogin = async () => {
    const { error } = await supabase.auth.signInWithOAuth({
      provider: 'github', // 替换为你实际使用的认证提供商
      options: {
        redirect_to: process.env.NEXT_PUBLIC_SUPABASE_REDIRECT_URL
      }
    });

    if (error) console.error(error);
  };

  return <button onClick={handleOAuthLogin}>登录</button>;
}

服务器组件/API路由示例

import { createServerComponentClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';

export default async function LoginRoute() {
  const supabase = createServerComponentClient({ cookies });

  const { data, error } = await supabase.auth.signInWithOAuth({
    provider: 'github',
    options: {
      redirect_to: process.env.NEXT_PUBLIC_SUPABASE_REDIRECT_URL
    }
  });

  if (error) {
    return new Response(JSON.stringify({ error: error.message }), { status: 500 });
  }

  return Response.redirect(data.url);
}

3. 确认Supabase控制台的重定向URL列表

务必在Supabase控制台的Authentication > URL Configuration中,将本地和生产的重定向URL都添加到Redirect URLs列表:

  • http://localhost:3000
  • https://some-production-url.com

这一步是为了避免出现重定向地址不被允许的错误。

问题根源说明

你之前遇到data.url始终指向生产Site URL的情况,是因为未手动指定redirect_to时,Supabase会默认使用控制台设置的Site URL。只要在认证调用时传入动态的redirect_to参数,就能覆盖默认值,实现环境差异化跳转。


内容的提问来源于stack exchange,提问作者Mathias Riis Sorensen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:57:11