Hiding API keys with Firebase without rendering in the client side? [duplicate] - firebase

This question already has answers here:
Is it safe to expose Firebase apiKey to the public?
(10 answers)
Closed last month.
I'm looking for a secure way to handle API keys in my NextJS web app using Firebase.
I see the suggestion to "hide" the keys in an ENV file then make sure of the variables by calling something like process.env.NEXT_PUBLIC_MYSUPERSECRETKEY. This will still reveal the key in the source code when it renders on the client browser.
...
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
}
...
I tried to use the process.env.FIREBASE_API_KEY (with the .env.local file defining FIREBASE_API_KEY) form to keep the variable server-side but Firebase throws an error:
FirebaseError: Firebase: Error (auth/invalid-api-key).
I looked at some code on GitHub and saw people were defining the ENV in the next.config.js file but that has the same result of showing on the client-side as well:
next.config.js
module.exports = {
env: {
API_KEY: process.env.FIREBASE_API_KEY,
},
}
.env.local
FIREBASE_API_KEY="XXX"
firebaseApp.js
...
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
...
https://nextjs.org/docs/api-reference/next.config.js/environment-variables

When you choose a hosting platform, for example we will use vercel.
You will more than likely point vercel towards your GitHub repo for it to build the application from.
When configuring the project on vercel, in the project settings there will be fields to enter your environment variables into. This will take care of the potential security issue you are seeing.
See here: https://nextjs.org/docs/basic-features/environment-variables

Related

Firebase dynamic links Expo dev

Im trying to implement Firebase dynamic links into my react native app. I'm using expo dev since it clearly states here that Expo Go does not support firebase.
However when running const link = await dynamicLinks().getInitialLink() I keep getting Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()
Where am I supposed to initialize it? It's a bit hard to find documentation or any mention of initializing firebase for a react native app, all I can find is for a web and I'm missing a lot of the config params.
I did setup my app.json according to the these docs
Any help is highly appreciated.
It turns out my firebase config was missing non optional items, once I filled them out I initialized my app like so
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app(); // if already initialized, use that one
}
and the config min required is
export const firebaseConfig = {
apiKey: "my key",
projectId: "my project id",
appId:"my app id",
databaseURL:"my db url",
messagingSenderId:"my id",
storageBucket:"bucket"
};

React Native .env doesn't seem to work with firebase apiKey

It's been a little while since I've created a React Native project and I just started a new one today. I've gotten firebase set up, installed react-native-dotenv, and created a .env file with all of my firebase project variables. I've triple checked to be sure the apiKey is correct (I copy pasted it when I created the firebase project anyway), and the last time I've done something like this that was all I needed to do to get it to work. So here's what I have:
firebase.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
// Firebase changed up how it works since v9
// https://travis.media/how-to-use-firebase-with-react/
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APPID,
measurementId: process.env.REACT_APP_MEASUREMENT_ID,
};
const firebase = initializeApp(firebaseConfig);
export const firestore = getFirestore(firebase);
export const auth = getAuth()
My .env file is the root directory of my project has the matching variables. The last time I did this it worked just fine. Now, I found this documentation: https://firebase.google.com/docs/functions/config-env explaining how to use .env in your firebase environment. However, after setting up the appropriate firebase-tools, running firebase init Firestone, and the firebase deploy --only functions, it starts to work but then fails informing me that I need to be on the Blaze plan in order to do any of that. I am sure I'm probably overcomplicating the situation, but if I'm not then that means you have to jump on the paid plan just to be able to keep your apiKey in a secure location in your code? There must be something I'm missing.
I had the same issue here but I fixed it with the installation of react-native-dotenv
https://www.npmjs.com/package/react-native-dotenv

API key not valid for a firebase, nextjs, vercel project in local dev environment

This wasn't a problem before and is currently not a problem in my production deployment. But now I get this response when I start up my dev environment and try google OAuth signin:
"API key not valid. Please pass a valid API key."
This is my firebase setup:
// firebase.js
import "firebase/auth";
import firebase from "firebase/app";
if (typeof window !== "undefined" && !firebase.apps.length) {
firebase.initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECTID
})
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
}
export { firebase };
// .env.local
NEXT_PUBLIC_API_KEY=<private>
NEXT_PUBLIC_AUTH_DOMAIN=<private>
NEXT_PUBLIC_PROJECTID=<private>
When looking at the http request made from both environments, there are two differences in the urls:
deployed: https://www.googleapis.com/identitytoolkit/v3/relyingparty/getProjectConfig?key=(api key)=(some random number)
development: https://www.googleapis.com/identitytoolkit/v3/relyingparty/getProjectConfig?key=(api key)=(some random number)
The api keys are exactly the same but the (some random number) are different. I don't know if this reveals anything but that's all I can see that's different. I'm not sure as to what happened because this was working before both in dev and in the deployed version. Now it just works only in the deployed.

Cannot receive events from Google Measurement Protocol (Google Analytics v4)

I created an app in Firebase, and then found my target app (NodeJS CLI, Chrome extension, VSCode extension) could not use Firebase SDK, then I found the Google Measurement Protocol. And it turns out to be frustrating and failed to get events to show up in the console.
My request passed /debug/mp.collect:
fetch(
`https://www.google-analytics.com/mp/collect?api_secret=${SECRET}&firebase_app_id=${FIREBASE_APP_ID}`,
{
method: 'POST',
body: JSON.stringify({
app_instance_id: ${INSTANCE_ID},
events,
}),
}
)
1st problem I met is finding the api_secret
Official doc says:
An API SECRET generated in the Google Analytics UI. To create a new secret, navigate to:
Admin > Data Streams > choose your stream > Measurement Protocol > Create
What I get is:
OK then comes into firebase:
const firebaseConfig = {
apiKey: "xxx",
authDomain: "dev-ext.firebaseapp.com",
databaseURL: "https://dev-ext.firebaseio.com",
projectId: "test",
storageBucket: "dev-ext.appspot.com",
messagingSenderId: "123",
appId: "xxx",
measurementId: "xxx"
};
Looks like is this apiKey, and I tried, not working.
Then I found someone says use the secret here:
And I tried, not working.
2nd problem is the app_instance_id, what the hell is this?
Here is the original doc:
No clues for web and NodeJS case at all, and the ios, android links are pointing to Firebase SDK method. I was like "WTF, why will I read this if I could use the Firebase SDK?"
So I tried a generated uuid. And obviously, it's not working.
I have the same, issue. Ended up adding a new stream on analytics.google.com and switching to gtag.js.

firebase in chrome extension

I have put this in manifest:
"content_security_policy":"script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'"
In popup.html:
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
But each time I firebase variable is not defined (console say that)
You may refer with this related SO post. You encountered that error maybe because you are injecting the Firebase library by using document.body.append(...). Then, you're trying to access the Firebase library from inside your extension, but chrome extensions are sandboxed away from the web page. You injected the Firebase library into the web page, so it is not directly accessible to your extension. You may try to download the Firebase library JavaScript, and add the Firebase code to your chrome extension manifest.
It's also stated that there's an example chrome extension with Firebase in GitHub which you can use for reference: https://github.com/firebase/firebase-chrome-extension.
you need to initialise firebase with your api config in javascript
var config = {
apiKey: "AIzaSyAqFmfmNWi95nt6TemvBMjPepulwV5WyZg",
authDomain: "define-web-ext.firebaseapp.com",
databaseURL: "https://define-web-ext.firebaseio.com",
projectId: "define-web-ext",
storageBucket: "",
messagingSenderId: "217235378805"
};
firebase.initializeApp(config);
if you are using npm packages , get firebase packages according to your
framework .

Resources