Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Myo Paing Thu's avatar

Token Authorization header with passport in vue.js

Where can i put the Authorization header token in axios after dispatching login action with laravel passport authentication in a seprated vue.js project?I tried with setting it in main.js like this and doesnt work properly. After dispatching, In the QuestionIndex component, the axios call dont have the authorization header automatically. And by refreshing the page, it has the authorization header. I can fix this by putting the token header in QuestionIndex Component. But I dont think this is a proper way to do it. Please help me with this problem. In my main.js


const token = localStorage.getItem('access_token');
if (token) {
  axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}

In my login.vue

login(){
             this.$store
                .dispatch("login", this.form)
                .then(() => {
                    this.error = "";
                    this.$router.push({ name: "QuestionIndex" });
                })
                .catch(err => {
                    
                    console.log(err);
                });
        }

In my vuex store

   state: {
        token: localStorage.getItem('access_token') || null,
        user: {},
    },
    mutations: {
        setToken(state, data) {
            state.token = data.token;
            state.user = data.user;
        },
       
    },
    actions: {
       
        login({ commit }, credentials) {
            return axios.post("http://127.0.0.1:8000/api/login", credentials).then(( res ) => {
                localStorage.setItem('access_token', res.data.data.token);
                commit("setToken", res.data.data);
            });
        },
    },
    getters: {
        token: (state) => state.token,
    
    }
0 likes
1 reply
bait-dept's avatar

Hello,

To achieve this within a project I am developing I've extended the Axios default object and used interceptors to add the authorization token to every request axios will make.

import store from "@/store";
import Axios from "axios";

const axios = Axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    responseType: "json",
  },
});

axios.interceptors.request.use((config) => {
  const tokens = store.getters["auth/getTokens"];

  if (!tokens) {
    return config;
  }

  let token = tokens.access;

  if (config.url === api.refresh) {
    token = tokens.refresh;
  }

  config.headers.Authorization = `Bearer ${token}`;

  return config;
});

export default axios;

Then it's a matter of only using this axios where needed like in store.

Please or to participate in this conversation.