Static GitHub Issues

[326] How to authorize first request with bearer token?

prev: Strange loader behavior
next: HMR for vuex store

I am storing user's jwt token in the localStorage and I have added an interceptor to axios to attach the correct bearer token to the request.

import axios from 'axios';

import store from '~store';
import config from '../config';

const methods = ['get', 'post', 'put', 'patch', 'delete'];

function formatUrl(path) {
  const adjustedPath = /^\/.*$/.test(path) ? path : `/${path}`;
  const inBrowser = typeof window !== 'undefined';
  const protocol = config.isProduction ? 'https' : 'http';

  if (!inBrowser) {
    return `${protocol}://${config.apiHost}:${config.apiPort}${adjustedPath}`;
  }

  return `/api${adjustedPath}`;
}

axios.interceptors.request.use((cfg) => {
  try {
    // const token = store.state.userSession.token;
    const token = localStorage.getItem('token');

    if (token) {
      cfg.headers.common.Authorization = `Bearer ${token}`;
    }
  } catch (ignore) {
    // ignore
  }

  return cfg;
}, error => Promise.reject(error));

class ApiClient {
  constructor() {
    methods.forEach((method) => {
      this[method] = (path, ...args) => axios[method](formatUrl(path), ...args);
    });
  }
}

const client = new ApiClient();

export default client;

This works fine when a certain page is rendered on the client, but it doesn't work on the initial request, because server doesn't have access to localStorage (of course) :-). Is there a way to get the token before fetch method of some page is trying to get some data?

<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c280">#c280</a>)</em></sub></div>