axios-module
axios-module copied to clipboard
Random Q, does this module support keep alive?
Please check this as an example and let me know if I am doing this correctly or is there is any need to? Thanks :D
import moment from 'moment-timezone'
let https = undefined;
let httpsAgent = undefined;
if(process.server) {
https = require('https');
httpsAgent = new https.Agent({ keepAlive: true });
}
export default ({$axios, store}) => {
if(process.server) {
$axios.defaults.httpsAgent = httpsAgent;
}
$axios.defaults.timeout = 30000;
$axios.interceptors.request.use(request => {
const token = store.getters['Auth/getAccessTokens'].accessToken;
if (token) {
request.headers.common['Authorization'] = `Bearer ${token}`
}
if(process.browser) {
request.headers.common['x-timezone-olsen-tag'] = moment.tz.guess()
}
return request
})
}
Your solution sounds good @kgrosvenor
You can also use a server plugin directly to make the code cleaner:
// plugins/axios.server.js
import https from 'https'
// This will be shared during SSR (only in production)
const httpsAgent = new https.Agent({ keepAlive: true })
export default function ({ $axios, redirect }) {
if (!$axios.defaults.httpsAgent) {
$axios.defaults.httpsAgent = httpsAgent
}
}
Don't forget to add it in nuxt.config.js:
plugins: ['~/plugins/axios.server']