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

Next.js中.env文件失效问题求助(OpenAI API+TypeScript)

问题描述

在Next.js项目中使用OpenAI API时,直接在代码中硬编码API密钥能正常运行,但将密钥移至.env(或.env.local)文件后,出现以下错误:

Error: The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).

服务器控制台中console.log(apiKey)能正常打印密钥,但OpenAI客户端初始化失败。不想通过NEXT_PUBLIC_前缀公开密钥,怀疑是代码在客户端渲染导致密钥返回undefined。

相关代码:

import OpenAI from "openai";

const apiKey: string = process.env.OPENAI_API_KEY;
const assistantId: string = process.env.OPENAI_ASSISTANT_ID;

console.log(apiKey)
console.log(assistantId)

// Check if API key is provided
if (!apiKey) {
    console.error("The OPENAI_API_KEY environment variable is missing or empty.");
}

const openai = new OpenAI({ apiKey: apiKey });
解决方法
  • 确保代码运行在服务器端环境:Next.js中,不带NEXT_PUBLIC_前缀的环境变量仅能在服务器端代码中访问。如果你的代码在客户端组件(添加了'use client'指令)中,客户端运行时process.env.OPENAI_API_KEY会是undefined,导致报错。

    • 迁移到API路由:创建app/api/openai/route.ts,在该文件中初始化OpenAI客户端并处理请求,前端通过fetch调用此API路由。
    • 使用Server Components:Next.js 13+ App Router中,移除组件的'use client'指令,将其设为Server Component,直接在组件中初始化客户端。
    • 使用Server Actions:定义带'use server'指令的异步函数,在函数内部处理OpenAI逻辑,前端调用该函数完成交互。
  • 重启开发服务器:Next.js热重载可能未加载最新的环境变量,停止当前npm run dev进程后重新启动,确保.env.local中的变量被正确加载。

  • 检查.env文件格式:环境变量值不能加引号,正确格式应为:

    OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx
    OPENAI_ASSISTANT_ID=asst-xxxxxxxxxxxxxxxxxxxxxxxx
    

    若添加引号,引号会被当作密钥的一部分,导致OpenAI验证失败。

  • 严格校验变量后初始化客户端:修改代码,确保在初始化前确认变量存在,避免类型断言导致的潜在问题:

    import OpenAI from "openai";
    
    const apiKey = process.env.OPENAI_API_KEY;
    const assistantId = process.env.OPENAI_ASSISTANT_ID;
    
    if (!apiKey) {
      throw new Error("The OPENAI_API_KEY environment variable is missing or empty.");
    }
    if (!assistantId) {
      throw new Error("The OPENAI_ASSISTANT_ID environment variable is missing or empty.");
    }
    
    const openai = new OpenAI({ apiKey });
    
  • 排查环境变量冲突:确认当前运行环境对应的.env文件(开发用.env.local,生产用.env.production)中变量正确,避免不同环境的文件互相覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 08:46:17