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?