Comprehensive Vue.js Authentication Setup: Step-by-Step Tutorial for Beginners

Vue.js is a popular JavaScript framework used for building interactive web applications. Setting up authentication is a crucial step for many projects, ensuring secure access to user-specific data. This tutorial provides a comprehensive, step-by-step guide to implementing authentication in Vue.js for beginners.

Prerequisites

  • Basic understanding of Vue.js and JavaScript
  • Node.js and npm installed on your machine
  • Vue CLI installed globally
  • Knowledge of RESTful APIs

Setting Up the Vue.js Project

Start by creating a new Vue.js project using Vue CLI. Open your terminal and run:

vue create auth-tutorial

Navigate into the project directory:

cd auth-tutorial

Run the development server:

npm run serve

Installing Required Packages

To handle authentication, we’ll use Axios for HTTP requests and Vue Router for navigation. Install them:

npm install axios vue-router

Configuring Vue Router

Create a router file in src/router/index.js and set up routes for login, register, and dashboard:

import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import Dashboard from '../views/Dashboard.vue';

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

Creating Authentication Views

Generate Vue components for login, registration, and dashboard:

mkdir src/views
touch src/views/Login.vue src/views/Register.vue src/views/Dashboard.vue

Login.vue

<template>
  <div>
    <h2>Login</h2>
    <form @submit.prevent="login">
      <input type="email" v-model="email" placeholder="Email" required />
      <input type="password" v-model="password" placeholder="Password" required />
      <button type="submit">Login</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      email: '',
      password: '',
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('/api/login', {
          email: this.email,
          password: this.password,
        });
        localStorage.setItem('token', response.data.token);
        this.$router.push('/dashboard');
      } catch (error) {
        alert('Login failed.');
      }
    },
  },
};
</script>

Register.vue

<template>
  <div>
    <h2>Register</h2>
    <form @submit.prevent="register">
      <input type="email" v-model="email" placeholder="Email" required />
      <input type="password" v-model="password" placeholder="Password" required />
      <button type="submit">Register</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      email: '',
      password: '',
    };
  },
  methods: {
    async register() {
      try {
        await axios.post('/api/register', {
          email: this.email,
          password: this.password,
        });
        this.$router.push('/login');
      } catch (error) {
        alert('Registration failed.');
      }
    },
  },
};
</script>

Dashboard.vue

<template>
  <div>
    <h2>Dashboard</h2>
    <p>Welcome to your dashboard!</p>
    <button @click="logout">Logout</button>
  </div>
</template>

<script>
export default {
  methods: {
    logout() {
      localStorage.removeItem('token');
      this.$router.push('/login');
    },
  },
};
</script>

Implementing Authentication Logic

Use navigation guards to protect routes requiring authentication. Update your router configuration:

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  if (to.meta.requiresAuth && !token) {
    next('/login');
  } else {
    next();
  }
});

Summary

This tutorial covered setting up a Vue.js project with basic authentication features. We created login, registration, and dashboard components, configured routing with protected routes, and managed authentication tokens. With these foundations, you can build more secure and feature-rich Vue.js applications.