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

Next.js初始加载时process.env读取.env变量失败求助

问题描述

我使用.env文件存储敏感数据,在.env文件中配置了CLIENT_SECRET=MY_KEY,并在SignWithGoogle组件中读取.env变量。组件代码如下:

import Image from "next/image";
import Link from "next/link";
import dotenv from 'dotenv'
dotenv.config({ path: "./.env" });
export const REDIRECT_URI = 'MY_URL';
const SignWithGoogle = () => {

    const GOOGLE_AUTH_URL = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${process.env.CLIENT_ID}&response_type=code&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile&redirect_uri=${REDIRECT_URI}`;
    return (
        <Link href={GOOGLE_AUTH_URL}>
            <button className="w-60 p-2 rounded-md border border-black hover:bg-slate-100 transition-all ease-in-out duration-500 flex justify-center gap-3 items-center font-bold">
                <Image alt="google" src="/google.png" width={30} height={30} loading="lazy" />
                Sign with Google
            </button>
        </Link>
    )
}
export default SignWithGoogle;

首次访问页面时,GOOGLE_AUTH_URL因process.env.CLIENT_ID未加载而包含undefined,刷新页面后URL可正常生成。尝试过用useEffect钩子设为状态变量,但无效,求解决办法。

解决办法
  • 移除dotenv依赖,使用Next.js内置环境变量机制
    Next.js自带环境变量加载逻辑,手动调用dotenv.config()会和内置机制冲突,导致首次加载变量未注入。直接删除以下代码:

    import dotenv from 'dotenv'
    dotenv.config({ path: "./.env" });
    
  • 给客户端环境变量添加NEXT_PUBLIC_前缀
    该组件是客户端渲染组件,Next.js默认只将带NEXT_PUBLIC_前缀的变量暴露给客户端。修改.env文件:

    NEXT_PUBLIC_CLIENT_ID=你的实际客户端ID
    

    组件中同步修改变量引用:

    const GOOGLE_AUTH_URL = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${process.env.NEXT_PUBLIC_CLIENT_ID}&response_type=code&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile&redirect_uri=${REDIRECT_URI}`;
    
  • 检查环境变量文件命名
    确保变量放在对应环境的文件中,比如开发环境用.env.development,生产环境用.env.production,文件名称无拼写错误。

  • 重启开发服务器
    修改环境变量后必须重启Next.js开发服务器,确保新变量被正确加载,避免缓存问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 11:12:05