如何用 .env 变量替换 Firebase 配置数据

问题描述 投票:0回答:2

我是 React Native 的新手,我一直在使用 Firebase 作为后端创建一个应用程序。我了解到,如果我只是从控制台页面复制 firebase 配置并将其粘贴到名为 firebaseConfig.js 的文件中,那就太危险了。

我创建了一个 .env 文件并编写了一些局部变量(如果我称它们正确的话,我不知道),用这些变量替换 firebase 配置信息,例如 apiKey。

不知道哪里错了。

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  authDomain: process.env.REACT_APP_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_PROJECT_ID,
  storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_APP_ID,
  // measurementId: "G-421JHRD4GK",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

# The .env file is used to store the API keys and other sensitive information. This file is not tracked by git, so it is not uploaded to GitHub. This is a good place to store API keys and other sensitive information that you do not want to be public.

REACT_APP_API_KEY = "config-info",
REACT_APP_AUTH_DOMAIN = "config-info",
REACT_APP_PROJECT_ID = "config-info",
... more

{
  "name": "byui-board-expo",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@react-native-community/datetimepicker": "6.2.0",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-navigation/bottom-tabs": "^6.4.0",
    "@react-navigation/native": "^6.0.13",
    "@react-navigation/stack": "^6.3.3",
    "expo": "~46.0.16",
    "expo-status-bar": "~1.4.0",
    "firebase": "^9.14.0",
    "native-base": "^3.4.21",
    "react": "18.0.0",
    "react-native": "0.69.6",
    "react-native-elements": "^3.4.2",
    "react-native-gesture-handler": "~2.5.0",
    "react-native-reanimated": "^2.12.0",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-svg": "12.3.0",
    "react-native-vector-icons": "^9.2.0",
    "react-native-webview": "^11.23.1",
    "react-native-xml2js": "^1.0.3"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

firebase google-cloud-firestore
2个回答

0
投票
我遇到了类似的问题,这是因为由于 process.env 只能在服务器端访问,客户端 sdk 无法访问这些变量,所以最好保留 firebase 配置不变并控制谁/哪些域可以从控制台读取/写入数据库。

© www.soinside.com 2019 - 2024. All rights reserved.