using axios with firebase , do i have to install firebase from npm? - reactjs

I have setup axios in my project like so,
In my src/ folder created a axios.js file that looks like so:
import axios from 'axios';
const instance = axios.create({
baseURL : 'https://myprojectname-11651.firebaseio.com/'
});
export default instance;
Then in my main component where i use axios i use it like so:
import axios from '../axios.js';
// removing code thats not necessary for this example
componentDidMount() {
// alert();
axios.get('/habits/badHabits.json')
.then( (resp) => {
console.log(resp);
})
}
I get a 401 error in my console, The dashboard for firebase seems to have changed from a year back and i am not unable to use axios with firebase like i used it over a year ago.
My database look like so:
How exactly do i use axios with firebase ? do i have to install firebase from npm ?

Yes you have to install firebase in your project using npm. It is initial process to configure your app with firebase. Then you have to add firebase credentials like
<script>
// Initialize Firebase
var config = {
apiKey: <YOUR_APP_KEY>,
authDomain: "<YOUR_APP_DOMAIN>",
databaseURL: "<YOUR_DATABASE_URL>",
projectId: "<YOUR_PROJECT_ID>",
storageBucket: "<YOUR_STORAGE_URL>",
messagingSenderId: "<YOUR_MESSENGER_ID>"
};
firebase.initializeApp(config);
</script>
Instruction:- You can find the above code here,
Firebase console > Project Settings (This is the gear icon opposite of "Project overview" text) > Your apps > (On same page you will have three choices to either use it for android, ios , web) > Add Firebase to your web app
Now that you have added these things you just need to use firebase functions to access the firebase storage, authentication, database.
Here is the link where you can find all your details
https://firebase.google.com/docs/web/setup
It will help you.

I have the feeling you are mixing up the Real Time Database REST API and the Firestore one.
From the picture in your question, you are using Firestore.
And for Firestore, "all REST API endpoints exist under the base URL https://firestore.googleapis.com/v1beta1/", see the doc here.
On the other hand, as detailed here, the Real Time DB REST API endpoints have a base URL like https://docs-examples.firebaseio.com/rest/.... which is similar to the URL in your question.

Related

Use .env vars in service worker - Create React App with Firebase

I'm using React with create-react-app and I have integrated Firebase Messaging for push notifications, it requires that you create a file in the public folder firebase-messaging-sw.js that is responsible to setup the service worker with firebase messaging to enable it.
It all works properly, my problem is using the firebase configuration keys directly into code, I know they're public keys, it is still really bad practice to hardcode them plus I have more than one environment (different firebaseConfigs) so it's even more frustating to keep them hardcoded.
The firebase-messaging-sw.js looks like this:
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');
const firebaseConfig = {
apiKey: 'example',
authDomain: 'example',
databaseURL: 'example',
projectId: 'example',
storageBucket: 'example',
messagingSenderId: 'example',
appId: 'example',
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (message) {
return self.registration.showNotification(
"Title",
"Message"
);
});
I've seen other questions like this How to use process.env in a React service worker
The solutions won't work, the cra-append-sw lib results in babel and webpack errors (those other libs are handled by CRA, so I don't mess with them)
My react-scripts version is 4.0.3
I don't have an actual answer, but I ran into the same problem and what I've been trying is to use the getToken() function. If you take a look to the docs, you can use the optional parameter ServiceWorkerRegistration to set a custom service worker.
const swRegistration = await navigator.serviceWorker.register('/src/firebase-messaging-sw.js');
const token = await fcm.getToken({
serviceWorkerRegistration: swRegistration,
});
Now the service worker can live inside the src directory, where it will be built and you can use env variables there. The thing is that if do it this way, I get a mimetype error when registering the service worker. You can see why this error ocurrs in the last answer of this forum.
Maybe you can build up from this and find a solution, good luck!

The current domain is not authorized for OAuth operations

hello everyone i have vite app and i used firebase google auth . it works fine but when i deploy it on vercel it give me this error :
The current domain is not authorized for OAuth operations. This will prevent signInWithPopup, signInWithRedirect, linkWithPopup and linkWithRedirect from working. Add your domain (todomarwenlabidi.vercel.app) to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.
this is my app link : https://todomarwenlabidi.vercel.app/
and i added the domain to authorized domains
look this photo
and this is my firebase config file :
const firebaseConfig = {
apiKey:import.meta.env.VITE_API_KEY ,
authDomain: "todo-app-97ae2.firebaseapp.com",
projectId: "todo-app-97ae2",
storageBucket: "todo-app-97ae2.appspot.com",
messagingSenderId: "540711457418",
appId:import.meta.env.VITE_APP_ID ,
};
You have to add the domains you use in the firebase authorized domains (see picture)

TypeError: firebase.auth() is not a function

I am setting a new firebase project. In the project I try to use firebase.auth() to create a new user with user email and password. However, when I use firebase serve and do a post request with the link in postman, i get an error which says firebase.auth is not a function.
I believe that there are questions regarding this issue, however I tried all the solutions that they have provided but none of the worked for me.
I tried:
- Adding require firebase/auth
- Deleting node modules and reinstalling firebase and firebase functions
- Import firebase and functions in different order
- Install firebase and functions in a different order
- Create a new project and install firebase and functions from scratch
const firebase = require('firebase');
const config = {
apiKey: "xxxxx,
authDomain: "xx",
databaseURL: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxx",
appId: "xxxxxx"
};
firebase.initializeApp(config);
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
//Signup route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle,
}
// TODO: validate data
firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res.status(201).json({ message: `user ${data.user.uid} signed up successfully`})
})
.catch(err => {
console.error(err);
return res.status(500).json({error: err.code});
});
});
Expected results: get status 201 on postman and created new user in firebase
Actual results: TypeError: firebase.auth is not a function. In the console and postman.
You should understand the difference of Firebase JavaScript SDK and Firebase Admin SDK for Node.
The Firebase JavaScript SDK is for the client side.
Firebase Admin SDK is for the server side(like the Cloud Functions).
So in your case, you should use admin.auth().createUser() .
See:
https://firebase.google.com/docs/web/setup
https://firebase.google.com/docs/admin/setup
It seems you want to instantiate the application using the client sdk instead of the server.
You need to use a private key instead, to get one go to your firebase console -> Project Overview -> Service accounts -> Generate new private key
then after you download and include the key in your project:
const admin = require('firebase-admin')
const serviceAccount = require('your_firebase_key/path/goes/here')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
Good luck!
I was able to resolve this issue by installing firebase as well as firebase-tools. I had initially only installed firebase-tools. Try running npm i firebase, restart the server firebase serve and see if you're still having the issue.

Possible to do Firebase social login + still have option to instead use manual email/password for creating/auth-ing accounts?

I'm thinking about implementing social authentication for an React app I want to create.
I see Firebase handles alot of that work for you for Google/Twitter/FB/GitHub auth.
But i still want to have an option to offer a manual signup (and for those users offer a manual login).
Is that possible? Like will Firebase store/auth manual users via their Authentication system? Or i need to have a separate auth system for that (with my own database/auth check outside of Firebase)?
I'm very new to this so just thought I'd ask. Some links to some React articles would be great. I only saw ones that implement social but not social+manual authentication (preferably via Firebase to cover all social logins vs manually setting each OAUTH system).
Thanks!
A single user account in Firebase Authentication can be linked with multiple providers. You can link those providers together after the user signs in with them.
For more on this, see the Firebase documentation on account linking. From there:
You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account. Users are identifiable by the same Firebase user ID regardless of the authentication provider they used to sign in. For example, a user who signed in with a password can link a Google account and sign in with either method in the future. Or, an anonymous user can link a Facebook account and then, later, sign in with Facebook to continue using your app.
Yes, its possible to make the authentication using firebase. Few dependencies you need to have in mind like, "react-native-firebase", for google sign-in "react-native-google-signin"
For Checking with Provider refer here
Android Setup
I am sharing sample code for Google Sign-in:
import { GoogleSignin } from 'react-native-google-signin';
import firebase from 'react-native-firebase'
const firebaseConfig = {
apiKey: firebaseConfigg.API_KEY,
authDomain: firebaseConfigg.AUTH_DOMAIN,
databaseURL: firebaseConfigg.DATABASE_URL,
projectId: firebaseConfigg.PROJECT_ID,
storageBucket: firebaseConfigg.STORAGE_BUCKET,
messagingSenderId: firebaseConfigg.GCM_SENDER_ID
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
login = async() => {
await GoogleSignin.hasPlayServices({ autoResolve: true });
const sigin = await GoogleSignin.configure({
iosClientId: '',
forceConsentPrompt: true,
scopes: ['profile', 'email']
}).then(async (success) => {
if (success) {
GoogleSignin.signIn().then((data) => {
console.log("--->> ", data);
const credential = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
firebase.auth().signInAndRetrieveDataWithCredential(credential).catch((error) => {
});
})
}
})
}

HTTP request: PUT 401 (Unauthorized)

I start to learn how to use firebase in my app. I follow the instruction in angular website and set the snippet in the index.html like:
<!-- The codes to add firebase -->
<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<!-- The core firebase client (required) -->
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-app.js"></script>
<!-- firebase-auth - Firebase Authentication (optional) -->
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>
<!-- firebase-database - The Firebase Realtime Database (optional) -->
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
<script>
var config = {
apiKey: ...,
authDomain: ...,
databaseURL: "https://...",
storageBucket: "...",
};
firebase.initializeApp(config);
</script>
And then I try to use HTTP request to put data like:
submitForm(personalInfo: PersonalInfo, educationsInfo: Education[], experiencesInfo: Experience[]): Observable<string>{
let body = JSON.stringify({personalInfo, educationsInfo, experiencesInfo});
let headers = new Headers({'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers});
console.log(body);
let url = this.firebaseUrl + 'apply-form.json';
return this.http.put(url, body)
.map((response) => {
return response;
})
.catch(this.handleError);
}
However, I got the following error:
PUT https://XXX.firebaseio.com/apply-form.json 401 (Unauthorized)
I don't know what the problem is. I'm new in using firebase and really need someone to help me. Thank you!
Your Firebase Database is by default only writeable by authenticated users. See the warning in the first blue box on the page on saving data to the database.
To work around this you can of course configure the security rules of your database to allow public access. But while that is typically fine during development, it's a bad idea as you get your app ready for release to people other than yourself.
The proper way to post data securely is to require the user to sign in with Firebase Authentication and then use that information to ensure they can only access data that they're authorized to. By using HTTP to access the Firebase Database, you've made this more difficult for yourself than needed. I recommend using the Firebase JavaScript SDK for both authentication and accessing the database.

Resources