Email authentication with firebase in nodejs
In this article i will explain you step by step how you can add email authentication with firebase in your nodejs application
Step 1: Create a Firebase Project or you can skip this step of you have already created your firebase project
-
Go to https://firebase.google.com and click on Get Started
-
Proceed to click on Create a project.
-
Enter a project name and check yes if you wish to add analytics to your project.
-
Wait for the project to be created.
Step 2: Create firebase credentials
-
Once your project created go to ProjectOverview->Project Settings and scroll below and click on Add App
-
Select Web option
Keep you credentials somewhere safe
Step 3: Enable email authentication from firebase
In order to enable email authentication from firebase
-
Go to Authentication from left panel of firebase
-
Go to sign-in method tab
-
Click on Add new provider
-
Select Email/Password and we are done
Step 4: Add firebase authentication code to firebase
- Install firebase
Go to your node project folder and install firebase
npm install firebase
- Copy paste the following code in your node js project and according to your node js project setup
import express from "express";
import path from "path";
import "dotenv/config";
import { initializeApp } from "firebase/app";
const app = express();
const port = 3000;
const __dirname = path.resolve();
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGE_SENDER_ID,
appId: process.env.APP_ID,
};
const firebase = initializeApp(firebaseConfig);
app.use(express.json());
app.use(express.static(path.join(__dirname, "src/public")));
app.get("/login", (req, res, next) => {
res.sendFile(__dirname + "/src/public/index.html");
});
app.post("/signup", async (req, res, next) => {
var email = req.body.email;
var password = req.body.password;
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(function (userRecord) {
console.log("User Created");
})
.catch(function (error) {
console.log("Something went wrong");
});
});
app.post("/authenticate", async (req, res, next) => {
var email = req.body.email;
var password = req.body.password;
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch(function (error) {
console.log(error.code);
console.log(error.message);
});
});
app.post("/logout", async (req, res, next) => {
firebase
.auth()
.signOut()
.then(
function () {
console.log("Logged out!");
},
function (error) {
console.log(error.code);
console.log(error.message);
}
);
});
app.listen(port, () => {
console.log(`Demo app listening on port ${port}`);
});