Axios

Framework Next.js 13 Fetching Axios

1. Create Axios Instance

const AxiosInstance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

2. Create Custom NextAPI to get all Next.js Header

// NextAPI.js
const NextHeader = require('next/headers');
const NextJSHeader = NextHeader.headers;
const NextJSCookie = NextHeader.cookies;

const getAllNextHeaderList = async () => {
  let next_headers = {};

  // Get all next header as list
  NextJSHeader().forEach((value, key) => {
    next_headers[key] = value;
  });

  return next_headers;
}

module.exports = {
  getAllNextHeaderList,
  NextJSHeader,
  NextJSCookie,
}

3. Extend the Axios Instance to pre-process Next.js Header and auth token

const NextAPI = require('./NextAPI');

AxiosInstance.interceptors.request.use((config) => {
  // Auth cookie to bearer token
  let cookie_auth_token = NextAPI.NextJSCookie().get('token')
  let auth_headers = {};
  if (cookie_auth_token) {
    auth_headers.Authorization = `Bearer ${cookie_auth_token.value}`;
  }

  // Next.js Header
  let next_headers = await NextAPI.getAllNextHeaderList();

  // merge headers and the custom header will overwrite next header
  config.headers = { 
    ...next_headers, 
    ...auth_headers,
    ...config.headers
  };

  return config;
});

Refrence