Standalone APIService needs access to redux or NextJS ctx for getting token

I have a standalone APIService.js which is used across my NextJS Application, it does a few things, but the main thing is setting the BASE_URL and if the user has logged in (should have a token in a cookie, or in a header cookie – this then dispatches into redux).

Basically I think I need this APIService to either; detect when there is a cookie on the machine (it does) or if its server-side rendered and get it from the header; or what I think is better – is to listen for changes to redux, and take the token from the redux store.

This is my APIService here;

    import axios from 'axios';
    import { Cookies } from 'react-cookie';
    import { API_URL } from './constants';

    const config = {
      baseURL: API_URL,
    const cookies = new Cookies();
    const APIService = axios.create(config);

    APIService.interceptors.request.use((request) => {
      const token = cookies.get('token');
      request.headers.Authorization = token ? `Bearer ${token}` : '';
      return request;

    export default APIService;

to give an example of the NextJS page usage;

I have this function in my _app.js

  static async getInitialProps({ Component, ctx }) {
    if (ctx.isServer) {
      if (ctx.req.headers.cookie) {
        const token = getCookie('token', ctx.req);
        console.log('WHOAMI ', token);;
    } else {
      const { token } =;
      console.log('WHOAMI2 ', token);;

    return {
      pageProps: Component.getInitialProps
        ? await Component.getInitialProps(ctx)
        : {},

Do I need to connect() the APIService to Redux – if so how can I? I generally import the APIService into other components where I need to use my API, so i dont want to make drastic changes to it unless absolutely necessary.

I did add a context hook to the page itself to call the API client side, but this only works as a workaround for the fact I cannot get access to the header or token in the APIService as it has no context access.

So I could add a function like this to the pages, but I know its a horrid solution.

useEffect(() => {
}, []);

Source: ReactJs