NextJS 环境变量不起作用 [英] NextJS environment variables aren't working

查看:26
本文介绍了NextJS 环境变量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为此研究了至少一个小时,但到目前为止我很困惑.也许我不理解文档或媒体文章.但是,据我了解,NextJS(我已经安装了最新版本)提供了一个内置的环境变量解决方案.因此,不需要 dotenv 包.

由于设置了 NextJS,我需要做的就是创建一个 env.local 来存储我的 API_KEY 和其他敏感信息.然后,一旦我保存了更新后的文件,我应该能够访问 ${process.env.API_KEY} 并且可以在我的代码中的任何位置访问该值.p>

如果上述陈述属实,我无法让它发挥作用.

就我而言,我使用环境变量连接到 Firebase.在下面的代码中,它正在被实现.我收到 500 格式错误:

连接 GRPC 流错误.代码:3 消息:3 INVALID_ARGUMENT:项目 id parakeat-a1-7706,格式错误:它要么包含无效字符或太长.看看 https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects有关如何获取项目 ID 的说明.

import * as firebase from 'firebase/app';导入'firebase/auth';导入'firebase/firestore';导入火力基地/存储";导入firebase/分析";常量配置 = {apiKey:process.env.FIREBASE_API_KEY,authDomain:process.env.FIREBASE_AUTH_DOMAIN,数据库URL:process.env.FIREBASE_DATABASE_URL,projectId:process.env.FIREBASE_PROJECT_ID,storageBucket:process.env.FIREBASE_STORAGE_BUCKET,messagesSenderId:process.env.FIREBASE_MESSAGING_SENDER_ID,appId:process.env.FIREBASE_APP_ID,测量ID:process.env.FIREBASE_MEASUREMENT_ID,};//初始化 Firebase尝试 {firebase.initializeApp(config);} 捕捉(错误){//我们跳过已经存在"消息是//当我们热重载时不是一个实际的错误如果(!/已经存在/.test(err.message)){console.error('Firebase 初始化错误', err.stack);}}//const firebaseAnalytics = firebase.analytics();常量 firebaseStorage = firebase.storage();常量 firebaseFirestore = firebase.firestore();出口 { firebaseStorage, firebaseFirestore };

上面显示的ID是正确的,那么有什么问题吗?为什么我直接把实际值放进去跳过它成功连接的process.env?

解决方案

默认情况下,通过 .env.local 加载的所有环境变量仅在 Node.js 环境中可用(在 getStaticProps 等方法中),这意味着它们不会暴露给浏览器.

为了向浏览器公开变量,您必须在变量前面加上 NEXT_PUBLIC_.例如:

NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk

文档

I've been poking around with this for at least an hour and so far I'm stumped. Perhaps I'm not understanding the docs or the medium articles. But, as I understand it NextJS (I have have the latest version installed) provides a built in env variable solution. So, there is no need for the dotenv package.

Since NextJS is setup all I would need to do is create an env.local to store my API_KEY and other sensitive information. Then, once I save that updated file, I should be able to access ${process.env.API_KEY} and have access to that value anywhere in my code.

Provided the above statements are true, I'm not able to get that to work.

In my case I'm using environmental variables to connect to Firebase. In the code below it's being implemented. I get a 500 malformed error:

Connection GRPC stream error. Code: 3 Message: 3 INVALID_ARGUMENT: 
Project id parakeat-a1-7706, is malformed: it either contains invalid 
characters or is too long. Look at https://cloud.google.com
/resource-manager/docs/creating-managing-projects#identifying_projects 
for instructions in how to get a project's id.

import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';
import 'firebase/analytics';

const config = {
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  projectId: process.env.FIREBASE_PROJECT_ID,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.FIREBASE_APP_ID,
  measurementId: process.env.FIREBASE_MEASUREMENT_ID,
};
// Initialize Firebase
try {
  firebase.initializeApp(config);
} catch (err) {
  // we skip the "already exists" message which is
  // not an actual error when we're hot-reloading
  if (!/already exists/.test(err.message)) {
    console.error('Firebase initialization error', err.stack);
  }
}

// const firebaseAnalytics = firebase.analytics();
const firebaseStorage = firebase.storage();
const firebaseFirestore = firebase.firestore();

export { firebaseStorage, firebaseFirestore };

The ID is correct shown above, so what's wrong? Why is it that if I put the actual value directly in and skip the process.env it successfully connects?

解决方案

By default all environment variables loaded through .env.local are only available in the Node.js environment (in methods like getStaticProps), meaning they won't be exposed to the browser.

In order to expose a variable to the browser, you have to prefix the variable with NEXT_PUBLIC_. For example:

NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk

Docs

这篇关于NextJS 环境变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆