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
I have used the above solution before but later on needed to include my .env variables in the bundle which is why I used the next.config.js file to house my variables.
Check this link to their documentation for reference:
Nextjs - next.config.js
Related
I'm coding a web application with Vue, Vue router, Vite and Firebase to handle the auth. To intialize my Firebase application I use the .env and to get the firebase variables (like VUE_APP_API_KEY, VUE_APP_AUTH_DOMAIN, etc...) in my firebase.js file I use process.env.VUE_APP_MY_VARIABLE. However when I go to my main page I've got an error in my browser's console.
Here is the error in the console:
Uncaught ReferenceError: process is not defined at firebase.js:6:13
So I've tried to use import.meta.env instead of process.env but for all my variables in the .env file, it returns me undefined. I've tried too to define all my variables in the vite.config.js like this but it still returns me undefined:
export default defineConfig({
plugins: [vue()],
define: {
"process.env.VUE_APP_MY_VARIABLE": process.env.VUE_APP_MY_VARIABLE
}
})
I'm sure that all my variables are indeed declare in the .env file because my IDE propose me all the good name with the auto-completion. In doubt I've tried to rename the .env file by .env.local but it's still the same.
Here is my firebase.js file's code:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth"
import { getFirestore } from "firebase/firestore"
const firebaseConfig = {
apiKey: process.env.VUE_APP_API_KEY,
authDomain: process.env.VUE_APP_AUTH_DOMAIN,
projectId: process.env.VUE_APP_PROJECT_ID,
storageBucket: process.env.VUE_APP_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_MESSAGING_SENDER_ID,
appId: process.env.VUE_APP_APP_ID
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, db };
So can anyone help me to solve my error ?
(PS: I apologize if my English wasn't perfect)
Only variables prefixed with VITE_ are exposed. Source
Vite uses import.meta.env
I am using Next.js to fetch data from my Firestore Database, but I keep getting an error in the console, stating that GET (FirestoreDatabaseURL) 404 (not found).
When I try any other json database such as myfakestore or jsonplaceholder, my code works (I tried both getServerSideProps and fetching with UseState), works beautifully. But not from my own database. Tried with Postman, but it won't work either.
I have tried to find different ways to get the database URL, but I am only finding this one format:
https://PROJECTID.firebaseio.com
The server is in us-central, which also helps determine the URL.
While testing around, I have gotten the error FetchError: invalid json response body at https://PROJECTID.firebaseio.com/ reason: Unexpected token F in JSON at position 0
Which I came to find out that it's not actually returning json, but HTML.
Just for context, this is my working code:
const [showProducts, setShowProducts] = useState()
const apiData = 'https://celeste-73695.firebaseio.com/'
let displayProducts
function pullJson () {
fetch(apiData)
.then(response => response.json())
.then(responseData => {
displayProducts = responseData.map(function(product){
return (
<p key={product.id}>{product.title}</p>
)
})
console.log(responseData)
setShowProducts(displayProducts)
})
//return
}
useEffect(() => {
pullJson()
},[])
And my firebase.js file
import firebase from 'firebase';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
export default db;
Can anybody point me in the right direction?
Thanks in advance.
The databaseURL property is for the Firebase Realtime Database, which you probably didn't create yet. The databaseURL property is not necessary to use Firestore though, so you should be able to access that with just the configuration data you have.
You may have created the realtime database but not have configured it with firebase config. I recommend you to go through this documentations for the realtime database.
To configure the firebase firestore you need to do the following:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
And make sure to export the db reference as will be used in your project.
After that you can start using the firestore like documented here as you have tried to use it with URL you may have to change the implementation for using it like shown in above documentations
I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.
I am creating a web app that uses Vue webpack with firebase. I would like to have my firebase credentials automatically change when i use firebase use <some_alias> on the firebase cli. In other projects, this simply meant including the /__/firebase/init.js file of firebase hosting. In this project, I am using the npm firebase library and can load in a specific firebase set of credentials with
import firebase from 'firebase'
var config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
firebase.initializeApp(config)
export default {
database: firebase.database,
storage: firebase.storage,
auth: firebase.auth
}
However, this does not get my credentials based on my current firebase workspace. Instead, I would like something like
import firebase from 'firebase'
const fbcli = require('firebase-tools');
export const getFirebaseInstance = () => {
return fbcli.setup.web().then(config => {
firebase.initializeApp(config)
return firebase
});
}
though synchronous. Is there any way to synchronously load in my firebase credentials?
This was solved by checking window.location.host when in the prod environment and having a production config object if the host was our production hostname and reading from the values of a configuration file otherwise.
Try using fs.writeFileSync as described in this example from a firebase blog post about reading credentials:
const fbcli = require('firebase-tools');
const fs = require('fs');
// by default, uses the current project and logged in user
fbcli.setup.web().then(config => {
fs.writeFileSync(
'build/initFirebase.js',
`firebase.initializeApp(${JSON.stringify(config)});`
);
});
After upgraded to Firebase 3.2.0 (react-native 0.30), I'm trying to set a TIMESTAMP as described in the docs:
import Firebase from 'firebase'
...
let config = {
apiKey: `${ Config.firebase.apiKey }`,
authDomain: `${ Config.firebase.authDomain }`,
databaseURL: `${ Config.firebase.databaseURL }`,
storageBucket: `${ Config.firebase.storageBucket }`
}
const firebase = Firebase.initializeApp(config)
const created_at = firebase.database.ServerValue.TIMESTAMP
then I get
created_at = undefined
when debugging with Chrome' Developer Tools, firebase.database is a function without any ServerValue in it.
Any idea ?
Try this syntax:
import Firebase from 'firebase'
and then:
Firebase.database.ServerValue.TIMESTAMP
This works for me
import RNFirebase from "react-native-firebase"
data.timestamp = RNFirebase.database.ServerValue.TIMESTAMP;
In my case, even though I was using Firestore for all my data storage/retrieval using the web JS client, I had to import the Firebase Database libary at the start of my HTML like so
<script defer src="/__/firebase/7.17.1/firebase-database.js"></script>
Simply having <script defer src="/__/firebase/7.17.1/firebase-firestore.js"></script> is not enough. After loading the database module, then I could access firebase.database stuff, like ServerValue.TIMESTAMP
In my case, since I am using Firestore, then I used firebase.firestore.Timestamp.now() instead of the firebase.database bits above.