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

Next.js 14 App Router中lib文件夹无法读取环境变量问题

Next.js 14 App Router环境变量读取失效解决方案(Server Action场景)

核心问题说明

Next.js 14 App Router会自动加载根目录的.env文件,无需手动引入dotenv,但以下几个常见规则容易导致变量读取失败:


解决步骤

  • 检查环境变量命名与格式

    • 确保.env文件中变量名与代码中process.env.XXX完全一致(大小写敏感),格式如下:
      CONNECTION_STRING=你的Azure存储连接字符串
      CONTAINER_NAME=你的Blob容器名称
      
    • 不要给变量值加引号(除非值包含特殊字符需要转义),等号前后不要加空格。
  • 重启开发服务器
    修改.env文件后必须重启npm run dev/yarn dev,否则新变量不会被加载。

  • 移除手动dotenv配置
    Server Action(带'use server'指令)属于服务端执行逻辑,Next.js会自动处理环境变量加载,无需添加import dotenv from 'dotenv'或dotenv.config(),手动引入反而可能干扰默认逻辑。

  • 验证变量加载状态
    可以在next.config.js中打印变量,确认Next.js是否正确读取:

    /** @type {import('next').NextConfig} */
    const nextConfig = {};
    
    console.log("CONNECTION_STRING:", process.env.CONNECTION_STRING);
    module.exports = nextConfig;
    

    重启服务器后查看终端输出,若此处能读到变量,说明.env文件无问题,需检查代码中的引用逻辑。

  • 确认Server Action调用方式
    确保uploadToAzureBlobStorage的调用符合Server Action规范:在Client Component中通过表单提交,或直接调用带'use server'的函数,避免在纯客户端逻辑中直接触发(可能导致上下文丢失)。


修正后的代码示例

"use server";

import { BlobServiceClient } from "@azure/storage-blob";

async function uploadToAzureBlobStorage(file: File) {
  console.log("Function is invoking");
  try {
    const azureString = process.env.CONNECTION_STRING;
    console.log("Azure Storage connection string:", azureString);

    if (!azureString) {
      throw new Error("Azure Storage connection string is not set");
    }

    const containerName = process.env.CONTAINER_NAME;
    console.log("Container name:", containerName);
    if (!containerName) {
      throw new Error("Azure Blob container name is not set");
    }

    const blobServiceClient = BlobServiceClient.fromConnectionString(azureString);
    const containerClient = blobServiceClient.getContainerClient(containerName);

    const fileKey = `uploads/${Date.now().toString()}-${file.name.replace(/ /g, "-")}`;
    console.log("File key for upload:", fileKey);

    const blockBlobClient = containerClient.getBlockBlobClient(fileKey);
    await blockBlobClient.uploadBrowserData(file);
    console.log("Upload successful:", fileKey);

    return {
      file_key: fileKey,
      file_name: file.name,
    };
  } catch (error: unknown) {
    console.error("Error uploading to Azure Blob Storage:", (error as Error).message || "Unknown error");
    throw error;
  }
}

export default uploadToAzureBlobStorage;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:17:53