Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we create a user with Firebase Auth in node.js?

I'm trying to create user account using Firebase auth in nodejs. It doesn't work and I don't know why. Here's the code and the error generated by nodejs:

var config = {.......}; // i can't share the config

var app = firebase.initializeApp(config);

var db = app.database();
var auth = app.auth();

auth.createUserWithUsernameAndPassword("[email protected]", "@NewPassWord").then(
    function(user){ console.log(user);},
    function(error){ console.error(error);}
);

Error generate by NodeJS:

TypeError: Object [object Object] has no method 'createUserWithUsernameAndPassword'
    at Object.<anonymous> (/home/antonio/Projects/firebase/app.js:20:6)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3
like image 879
Antonio Blaise Avatar asked May 27 '16 14:05

Antonio Blaise


People also ask

How do I use Firebase Auth in node JS?

Click on the web to create a web app. Go to Firebase Settings>Service Account >Generate a new Key. This Key should be remain private, It is advised to keep this in environment variables. Now go to Authentication tab and turn on Sign in with Google.

Can you add users to Firebase?

Add a memberSign in to Firebase. Click. , then select Permissions. On the Permissions page, click Add member.


1 Answers

I finally got it working in Node.js. Is your app an instance of firebase-admin by any chance, as opposed to firebase?

In my express app I initialise firebase in the main app.js like so (pretty standard fare):

var firebase = require("firebase");

firebase.initializeApp
({
  apiKey: "xxx",
  authDomain: "xxx",
  databaseURL: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx"
});

Then in the route responsible for creating users I do this:

var firebase = require("firebase");

router.post('/register', function(req, res, next)
{
  var email = req.body.email;
  var password = req.body.password;

  firebase.auth().createUserWithEmailAndPassword
  (
    email,
    password
  )
  .then(function(userRecord)
  {
    res.location('/user/' + userRecord.uid);
    res.status(201).end();
  })
  .catch(function(error)
  {
    res.write
    ({
      code: error.code
    });
    res.status(401).end();
  });
});
like image 126
Hayko Koryun Avatar answered Nov 07 '22 23:11

Hayko Koryun