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

Next.js中createClientComponentClient无法读取Supabase环境变量求助

问题:Next.js + Supabase 无法读取环境变量导致注册失败

环境变量配置(.env.local)

NEXT_PUBLIC_SUPABASE_URL=https://myprojecturl.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=<mykeyhere>

相关代码

page.js

"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";

// Components
import AuthForm from "../AuthForm";

export default function Signup() {
    const router = useRouter();
    const [error, setError] = useState("");
    const handleSubmit = async (e, email, password) => {
        e.preventDefault();
        setError("");
        console.log(
            `in handleSubmit(), reading env vars: ${process.env.NEXT_PUBLIC_SUPABASE_URL} and ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`
        ); // 此处输出两个变量均为undefined
        const supabase = createClientComponentClient();
        const { error } = await supabase.auth.signUp({
            email,
            password,
            options: {
                emailRedirectTo: `${location.origin}/api/auth/callback`,
            },
        });

        if (error) {
            setError(error.message);
        }

        if (!error) {
            router.push("/verify");
        }
    };
    return (
        <main>
            <h2 className="text-center">SignUp</h2>
            <AuthForm handleSubmit={handleSubmit} />
            {error && <div className="error">{error.message}</div>}
        </main>
    );
}

AuthForm.js

"use client";
import { useState } from "react";

export default function AuthForm({ handleSubmit }) {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    return (
        <form onSubmit={(e) => handleSubmit(e, email, password)}>
            <label>
                <span>Email:</span>
                <input
                    type="email"
                    onChange={(e) => setEmail(e.target.value)}
                    value={email}
                    required
                />
            </label>
            <label>
                <span>Password:</span>
                <input
                    type="password"
                    onChange={(e) => setPassword(e.target.value)}
                    value={password}
                    required
                />
            </label>
            <button className="btn-primary">Submit</button>
        </form>
    );
}

报错信息

Unhandled Runtime Error
Error: either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!

已做排查

  • 对比教程代码库,代码完全一致
  • 匹配并重装Supabase相关依赖版本,问题依旧
  • 在submit函数中直接读取环境变量,结果均为undefined

解决方案

  1. 重启开发服务器:Next.js仅在启动时加载环境变量,修改.env.local后必须重启npm run dev或yarn dev进程,新的环境变量才会生效。
  2. 校验环境变量命名:确保变量名严格为NEXT_PUBLIC_SUPABASE_URL和NEXT_PUBLIC_SUPABASE_ANON_KEY,注意大小写、下划线不能少,避免拼写错误。
  3. 确认文件位置:.env.local必须放在项目根目录,不能放在src或其他子文件夹中,否则Next.js无法识别。
  4. 手动传入密钥(临时方案):如果上述方法无效,可以在创建客户端时手动传入参数绕过环境变量读取问题:
const supabase = createClientComponentClient({
  supabaseUrl: "你的Supabase项目URL",
  supabaseKey: "你的Supabase匿名密钥"
});

注意:此方法仅作临时测试,生产环境仍需通过环境变量管理密钥。
5. 检查依赖兼容性:确保@supabase/auth-helpers-nextjs版本与你的Next.js版本匹配,比如Next.js 13+需使用最新版的auth-helpers包。

内容的提问来源于stack exchange,提问作者S Anwar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:13:13