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

Next.js如何在/lib中读取.env变量且不暴露给客户端

解决Next.js中/lib模块读取私有环境变量的问题

问题根源

你的代码报错TypeError: Expected parameter accessToken,核心原因有两点:

  1. 模块顶级作用域的await client.getEntries()会在模块加载时执行,如果这个模块被客户端代码引入,浏览器环境无法读取不带NEXT_PUBLIC_前缀的私有环境变量,导致process.env.CONTENTFUL_ACCESS_KEY为空。
  2. 私有环境变量(不带NEXT_PUBLIC_)仅在Next.js的服务器端环境可用,客户端无法访问。

解决方案

1. 确认环境变量配置

在项目根目录的.env.local文件中正确配置变量,不要添加NEXT_PUBLIC_前缀:

CONTENTFUL_SPACE_ID=你的空间ID
CONTENTFUL_ACCESS_KEY=你的私有访问令牌

2. 调整代码结构,确保仅在服务器端执行数据获取

将数据获取逻辑移到函数内部,避免模块顶级的异步操作,同时确保getAuthors仅在服务器端环境被调用(比如服务器组件、API路由、getStaticProps/getServerSideProps中)。

修正后的代码示例:

import { createClient } from "contentful";

// 确保客户端仅在服务器端初始化
const getContentfulClient = () => {
  return createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_ACCESS_KEY,
  });
};

export async function getAuthors() {
  const client = getContentfulClient();
  const auth_data = await client.getEntries({ content_type: "author" });
  
  const authors = auth_data.items.map(item => ({
    authorSlug: item.fields.name
      .toString()
      .replace(/ /g, "-")
      .toLowerCase(),
    authorContent: item.fields.description,
    authorFrontMatter: {
      title: item.fields.name,
      image: "https:" + item.fields.image.fields.file.url,
    },
  }));
  
  return authors;
}

3. 确保函数仅在服务器端调用

  • App Router:在服务器组件中直接调用getAuthors(服务器组件默认在服务器端执行):
    // app/authors/page.js
    import { getAuthors } from "@/lib/your-file-name";
    
    export default async function AuthorsPage() {
      const authors = await getAuthors();
      return (
        <div>
          {authors.map(author => (
            <div key={author.authorSlug}>{author.authorFrontMatter.title}</div>
          ))}
        </div>
      );
    }
    
  • Pages Router:在getStaticProps或getServerSideProps中调用,将数据传递给页面组件:
    // pages/authors.js
    import { getAuthors } from "../lib/your-file-name";
    
    export default function AuthorsPage({ authors }) {
      return (
        <div>
          {authors.map(author => (
            <div key={author.authorSlug}>{author.authorFrontMatter.title}</div>
          ))}
        </div>
      );
    }
    
    export async function getStaticProps() {
      const authors = await getAuthors();
      return {
        props: { authors },
      };
    }
    

关键说明

  • 不带NEXT_PUBLIC_的环境变量只会被注入到服务器端代码中,只要你的getAuthors函数仅在服务器端执行(比如上述场景),就能正常读取这些变量,且不会暴露给客户端。
  • 避免在客户端组件中直接调用getAuthors,否则会再次出现环境变量无法读取的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:15:34