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

使用NEXT_PUBLIC_前缀将环境变量暴露至浏览器是否安全?敏感密钥风险与部署后可访问性咨询

Is It Safe to Use the NEXT_PUBLIC_ Prefix for Sensitive Secrets (Like API Keys) in Next.js?

Short answer: Absolutely not — this is a critical security mistake that will expose your sensitive data to anyone visiting your site. Let me break down why and what actually happens:

  • NEXT_PUBLIC_ variables get baked into client-side code: When you build your Next.js app, any variable prefixed with NEXT_PUBLIC_ is injected directly into the static JavaScript, CSS, or HTML files sent to the browser. Anyone can easily find these values by:
    • Viewing your page's source code (right-click → "View Page Source")
    • Digging through bundled JS files in the browser dev tools' "Sources" tab
    • Scraping your site's public static assets
  • Sensitive secrets belong in server-side-only variables: Non-public environment variables are designed to live exclusively in Node.js contexts (like API routes, getServerSideProps, getStaticProps, or server middleware). These parts of your code never get sent to the browser, so your secrets stay protected.
  • How to safely handle client-side API calls: If you need to call an external API from the client, create a Next.js API route as a proxy. Your client code calls this internal API route (no secrets needed), then your server-side route uses the non-public secret to interact with the external API. This way, sensitive data never leaves your server.

Here's a quick example:
If you have a secret API_SECRET=xyz123 (no NEXT_PUBLIC_ prefix), use it in /pages/api/proxy.js:

export default async function handler(req, res) {
  const response = await fetch('https://external-api.com/data', {
    headers: {
      Authorization: `Bearer ${process.env.API_SECRET}`
    }
  });
  const data = await response.json();
  res.status(200).json(data);
}

Then your client-side code calls /api/proxy instead of the external API directly — no secrets exposed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:32:44