DEV Community

Hilton Meyer
Hilton Meyer

Posted on • Originally published at hiltonmeyer.com on

3 3

Login user using firebase

Code for this can be found in the Github Branch

In the vuex auth store all that needs to be done is add the login functionality. The great thing about using actions for asynchronous functions and let the mutations handle the state changes is as you can see in this case the mutation is the same whether the user registered or logged in for both success or failure. So firebase does all the heavy lifting of handling the auth which is a world unto its own and we just manage the state using Vuex. The application will then reflect the current state.

import firebase from '@/firebase.js';

const userRef = firebase.firestore().collection('/user');

export default {
  async register({ commit }, user) {
    try {
      // Register user
      const registered = await firebase
        .auth()
        .createUserWithEmailAndPassword(user.email, user.password);
      console.log(registered);

      // Create userdata
      const userData = {
        id: registered.user.uid,
        username: user.username,
        email: user.email,
      };

      // Save user to DB
      const createUser = await userRef.add(userData);
      commit('authSuccess', createUser);
    } catch (err) {
      commit('authFail', err);
    }
  },
  async login({ commit }, user) {
    try {
      const loggedIn = await firebase
        .auth()
        .signInWithEmailAndPassword(user.email, user.password);
      console.log(loggedIn);

      const userData = {
        id: loggedIn.user.uid,
        username: user.username,
        email: user.email,
      };

      commit('authSuccess', userData);
    } catch (err) {
      commit('authFail', err);
    }
  },
};

Enter fullscreen mode Exit fullscreen mode

The next step will be to add a login form similar to the registration form and then start creating checks on the routing.

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay