LoginSignup
4
2

More than 3 years have passed since last update.

Nuxt.ts - axiosのheadersに常にtokenを付与する方法

Posted at

JWTのトークンをリクエストの度に付与するのが面倒で、この実装で実現できたのでメモ

plugins/axios.ts
import { Context } from '@nuxt/types';
import Cookies from 'js-cookie';

export default function ({ $axios }: Context) {
  $axios.onRequest((config) => {
    const token = Cookies.get('authToken');
    if (token) {
      config.headers.common['Authorization'] = 'Bearer ' + token;
    }
    return config;
  });
}
nuxt.config.js
export default {
  // ...
  plugins: ['@/plugins/axios'],
  // ...
}
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2