Tech Magazine

Laravel JWT Authentication – Vue Js SPA (Part 2)

25 23,795

Get real time updates directly on you device, subscribe now.

In this article, we will discuss the Laravel JWT Authentication - Vue Js SPA (Part 2). In this part, we will continue from where we leave in the tutorial (part 1).

Still, if you are not reading the previous part then please go and check it once for better understanding. In the previous part, Im describing the Laravel JWT Authentication in brief. You can learn how to make the API authentication using JWT.

Today, I will describe how we can setup Vue Js in Laravel application and how we can connect JWT API authentication with Vue Js frontend.

Setup Vue Js

Vue Js is already part of a Laravel application. You just need to execute the following command in your terminal and install the required dependencies.

npm install

After executing this command, you will see the node_modules folder in your Laravel application. This folder contains all the necessary node modules. You can read here the full process of Vue Js setup.

Then open your resource/views/welcome.blade.php file and replace the file content.

            {{ config('', 'Laravel') }}            


Create Default Component

Create a default component at resources/js/Index.vue. Open Index.vue and add the following code snippet into the file. Its like a default component, which is loaded first then other components can be added in the content div as per the app functionality.


Update app.js

Open app.js located at resources/js and update the following code snippet.

import './bootstrap'import Vue from 'vue'import Index from './Index'// Set Vue globallywindow.Vue = Vue// Load IndexVue.component('index', Index)const app = new Vue({  el: '#app'});

After that, you need to execute the following NPM command. This command can watch the changes in your app at the time of development.

npm run watch

Laravel JWT Vue Js


Setup Vue Js Packages for Authentication

Now, the basic Vue Js setup is ready with our Laravel application. Time to install the necessary package websanova/vue-auth and some of its dependencies such as vue-router , vue-axios, axiosand es6-promise for our authentication with Laravel JWT.

You can use the following command to install all these packages.

npm i @websanova/vue-auth vue-router vue-axios axios es6-promise

After successful installation, you need to create an auth configuration file at resources/auth.js and add the following code.

import bearer from '@websanova/vue-auth/drivers/auth/bearer'import axios from '@websanova/vue-auth/drivers/http/axios.1.x'import router from '@websanova/vue-auth/drivers/router/vue-router.2.x'/** * Authentication configuration, some of the options can be override in method calls */const config = {  auth: bearer,  http: axios,  router: router,  tokenDefaultName: 'laravel-jwt-auth',  tokenStore: ['localStorage'],    // API endpoints used in Vue Auth.  registerData: {    url: 'auth/register',     method: 'POST',     redirect: '/login'  },  loginData: {    url: 'auth/login',     method: 'POST',     redirect: '',     fetchUser: true  },  logoutData: {    url: 'auth/logout',     method: 'POST',     redirect: '/',     makeRequest: true  },  fetchData: {    url: 'auth/user',     method: 'GET',     enabled: true  },  refreshData: {    url: 'auth/refresh',     method: 'GET',     enabled: true,     interval: 30  }}export default config

In this configuration, we create some of the basic config variables. These configurations used for vue-auth. You can read more on Vue-Auth configuration on the official documentation.


Create Route File

Create a file router.js under the resources directory and add the following code.

import VueRouter from 'vue-router'// Pagesimport Home from './pages/Home'import About from './pages/About'import Register from './pages/Register'import Login from './pages/Login'import Dashboard from './pages/user/Dashboard'import AdminDashboard from './pages/admin/Dashboard'// Routesconst routes = [  {    path: '/',    name: 'home',    component: Home,    meta: {      auth: undefined    }  },  {    path: '/about',    name: 'about',    component: About,    meta: {      auth: undefined    }  },  {    path: '/register',    name: 'register',    component: Register,    meta: {      auth: false    }  },  {    path: '/login',    name: 'login',    component: Login,    meta: {      auth: false    }  },  // USER ROUTES  {    path: '/dashboard',    name: 'dashboard',    component: Dashboard,    meta: {      auth: true    }  },]const router = new VueRouter({  history: true,  mode: 'history',  routes,})export default router

In this file, we will be defined as the required routes. The meta parameter is used to define the access rules for each route.

Each of the routes contains path, name, component and meta parameter.

  • path is a route path, which accesses in our application.
  • name is a route name, we use route name to call the specific route.
  • component is loaded at a time for a route called.
  • meta is used to define the access rules for each route.
    • auth: undefined, its a public route.
    • auth: true, its available only for the authenticated users and auth: false, is available only for the unauthenticated users.


Create Components

Now, time to create required components such as home, register, login, dashboard, and etc as given below.

Home Component

Create home component at resources/js/pages/home.vue. This component is the home page of our application.


Register Component

Registration form - Create register component at resources/js/pages/register.vue.


Login Component

Login form - Create login component at resources/js/pages/Login.vue.


Dashboard Component

Dashboard.vue - Create dashboard component at resources/js/pages/user/Dashboard.vue.


Menu Component

Menu.vue - Create menu component at resources/js/components/Menu.vue. Its a reuseable component. We are going to use this component in Index.vue.


Index Component

Index.vue - component is the main component which is loaded by default. You can control this in your resources/js/app.js.


Update App.js

Finally, time to update resources/js/app.js. So open your app.js file and replace the code with the following code.

require('./bootstrap');import 'es6-promise/auto'import axios from 'axios'import Vue from 'vue'import VueAuth from '@websanova/vue-auth'import VueAxios from 'vue-axios'import VueRouter from 'vue-router'import Index from './Index'import auth from './auth'import router from './router'// Set Vue globallywindow.Vue = Vue// Set Vue routerVue.router = routerVue.use(VueRouter)// Set Vue authenticationVue.use(VueAxios, axios)axios.defaults.baseURL = `${process.env.MIX_APP_URL}/api/v1`Vue.use(VueAuth, auth)// Load IndexVue.component('index', Index)const app = new Vue({  el: '#app',  router});

In this file, we need to import the necessary Vue.js packages and other dependencies which we need at the time to application load.


Update Laravel “.env”

As you notify, Im using MIX_APP_URL variable for Axios base URL. But before using this you need to add this variable in your Laravel .env file.


Now, time to test the application. So Im using two different terminals or command prompt window to execute our Vue Laravel App.


Test Laravel Vue App

Open the first terminal and execute the following artisan command.

php artisan serve --port=9090

In the second terminal, we need to execute the following NPM command.

npm run watch

The above mention npm run watch command will detect all the file changes and compile those file immediately. You just need to refresh the browser.

Lets time to check the working of our Laravel Vue application.

Home Page

Laravel Vue Js Home Page

Login Page

Laravel Vue Js Login Page

Register Page

Laravel Vue Js Register Page

Everything works fine, but when you trying to reload any specific route such as login or register then we face error. It because of Laravel is currently configured only for the index route. You have to update the route/web.php route file and replace the following code with the existing.

// Route to handle page reload in Vue except for api routesRoute::get('/{any?}', function (){    return view('welcome');})->where('any', '^(?!api\/)[\/\w\.-]*');

After that, each route works fine.

When a user logged in the application then the user will redirect to its dashboard.

Laravel Vue Js Dashboard Page


In this tutorial, we will be discussing the Vue Js Setup and connect Laravel JWT Authentication with Vue App. This is the second part of the series, so you need to check part 1 for better understanding. In part 1 Im explaining the Laravel JWT Authentication.

Its just a start, still not enough in Vue Js. We will discuss more on Vue Js such as protecting route, error handling, user role management and many more.

You can get the complete source code on GitHub.

Please feel free to ask questions, and also send me your feedback so I can make improvement in this tutorial.

🙂 😉

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

  1. Maria Smith says

    Thanks Pankaj
    Great tutorial. More appreciated if you share this tutorial via GitHub repository.

  2. James says

    Hi Pankaj,

    As far as I know I followed your tutorial to the letter but I am getting the following console error:

    POST http://localhost:8000/undefined/api/v1/auth/login 405 (Method Not Allowed)

    Any suggestions? Do you have a working version of the code on Github?

    1. Code Briefly says

      Hi James,

      Please recheck all the step once and try again.
      Yes, I have a working version and soon I will create a GitHub repository for this.

    2. mr nice guy says

      I have the exact same problem… Hmm,

      1. Bonno says

        I have the exact same error: http://localhost:8080/undefined/api/v1/auth/login 404 (Not Found)
        I’m using vue cli 3 project with laravel.
        http://localhost:8080 is my vue project.
        http://localhost:8000 is my laravel project.
        So my baseURL is supposed to be http://localhost:8000/api/v1/auth/login

        When I try to hardcode i.e: axios.defaults.baseURL = ‘http:/localhost:8000/api/v1’ , I get error:
        POST http://localhost:8080/localhost:8000/api/v1/auth/login 404 (Not Found)

        1. Alvaro González says

          Hi, you need to leave it like this
          axios.defaults.baseURL = ‘/api/v1’

          That worked for me

          1. Martijn says

            Actually, re-running rpm run watch (and possibly artisan cache:clear) will add the new environment variable to your app

  3. d says


  4. David says

    Hi. Where do you save the token sent from server?
    As i see, upon successful login, it is sent in header.

    return response()->json([‘status’ => ‘success’], 200)->header(‘Authorization’, $token);

    Shouldn’t we save it in local storage or in cookie??


  5. Joan says

    Thanks for your great tuto!

    My issue is that I can register and login with postman. ok part 1. But when I try to “refresh” with postman (/api/auth/refresh/), from a logged user (authentication: Bearer tokenkey…) I get an “undefined variable ‘token'” from the refresh method.

    How does this method get the token to refresh?

    Thank you!

    1. Joan says

      I should add to my comment that the problem seems to be that token doesn’t persist. Even having set the option as ‘ttl’ => env(‘JWT_TTL’, 1440) in config/jwt.php


    2. Shawn says

      Author does not include that when using /api/auth/refresh you must pass the token as a a header. In Postman:

      Key: Authorization
      Value: Bearer

  6. alex says


  7. Cleber says

    Don’t work in Laravel 5.8,*:
    Method Illuminate\Auth\SessionGuard::refresh does not exist.

  8. Sakakido Kou says

    Thanks for sharing Pankaj!
    It works with the latest Laravel and VueJS.
    But the which is showed in span element is “[…]”. Can you help me to remove the double quotes and the square brackets, pls?

  9. Hello dude says

    what is the function of “auth.js”?

    still confused @_@

  10. diego says

    tengo una duda si es que se puede al momento de registrarse logearse directamente
    nose si tengo que modifcar el auth.js o en el componente register.vue
    app.success = true

    ya que al hacer esto no me deja entrar al dashboard

  11. Oawaldo says

    error, can not register at the moment. if the problem persists, contact administrator please if you help me I am registering a new user and I get this error I appreciate your helpplease if you help me I am registering a new user and give me this error I appreciate your help

  12. Luis says

    Hello, nice tutorial, I am trying to test it but I get errors: for example:

    /** @test */
    function a_user_can_login()
    $attributes = [

    $response = $this->post(‘/api/auth/login’, $attributes);
    ‘user’, ‘access_token’

    then I get this error: Expected status code 200 but received 401.(Unauthorized)
    What can I do?

    Thank you.

    1. Pankaj Sood says

      Hi Luis,
      It’s hard to get the reason why you face this 🙂
      Do some debugging and track your API.

  13. Luis says

    I modified my test like this:

    /** @test */
    function a_user_can_login()
    $attributes = [
    ‘password’=> bcrypt(’123546’)

    $response = $this->post(‘/api/auth/login’, $attributes);
    ‘user’, ‘access_token’

    I forgot to add the bcrypt function, but still I get the same error, I found out that it fails in AuthController.php

    * Get a JWT via given credentials.
    * @return \Illuminate\Http\JsonResponse
    public function login()
    $credentials = request([’email’, ‘password’]);

    ///here fails
    if (! $token = auth()->attempt($credentials)) {
    return response()->json([‘error’ => ‘Unauthorized’], 401);

    return $this->respondWithToken($token);

    it fails when trying to log in the user. it is so strange,

  14. Pragya says

    getting Token Signature could not be verified error. how to solve this

  15. Ben says

    Hi i tried to implement this ith your tutorial.

    Register is working fine,
    I can login but then i get this error :
    Failed to load resource: the server responded with a status of 400 (Bad Request) – /api/v1/auth/user:1
    When i refresh the page i get a blank page and the error :
    app.js:1630 GET http://laravue.test/api/v1/auth/refresh 500 (Internal Server Error)

    message: “Method Illuminate\Auth\SessionGuard::refresh does not exist.”,…}
    exception: “BadMethodCallException”
    file: “/Users/benoitheidingsfeld/DevProjects/vuexy-laravue/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php”
    line: 103
    message: “Method Illuminate\Auth\SessionGuard::refresh does not exist.”
    trace: [,…]

  16. jean says

    How can i retrieve the id of the user on login?

  17. Rahmad Subagiyo says

    Hi, i was followed your tutorial and get stuck after update app.js . i got error “Uncaught SyntaxError: Unexpected token ‘!’ “. how i can solve it? thanks for your answer, sir

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More