0

I have an application that uses NextJS with SSR requests (Axios) inside getServerSideProps.

I would like to know if there is a way to intercept Axios SSR requests and globally add header: { "X-FOO": "BAR" }.

I tried (Unsuccessfully):

export function getServerSideProps(context) {
  context.req.headers['X-FOO'] = "BAR";

  return {
    props: {},
  };
}

If I inject directly into every axios request configHeaders it works correctly:

export const getServerSideProps: GetServerSideProps = async(context) => {
  const { req } = context;
  const configHeaders = {
    headers: {
      'X-FOO': `BAR`,
    }
  };
      const data = await axios.create({
        baseURL: BASE_URL,
      }).get(`/path`, configHeaders);

      return {
        props: {
          data,
        },
      };
    }
  }

  return {
    props: {},
  };
};

I would to know if there's a way to add globally a header to SSR requests.

  • You should add these headers to the Axios instance on the client side, so that all your requests made by that instance have these headers. – lakshman.pasala Sep 06 '22 at 08:42
  • Does this answer your question: [How do I create configuration for axios for default request headers in every http call?](https://stackoverflow.com/questions/51794553/how-do-i-create-configuration-for-axios-for-default-request-headers-in-every-htt)? – juliomalves Sep 06 '22 at 18:41

1 Answers1

0

this article was of great help reference: https://lazypandatech.com/blog/NextJs/50/REST-API-Call-using-Axios-Interceptor-in-React-NextJs/

based on this article i will try breaking it down step by step

the task : integrate axios globally

Api service: rapi-api

I will be using typescript and OOP concepts to demonstrate this solution...

step 1:

create an abstract class, we will call this class "AxiosBaseService"

import axios, { AxiosInstance, AxiosRequestConfig } from "axios";

export abstract class AxiosBaseService {
  protected instance: AxiosInstance;
  protected token?: string;
  protected readonly baseURL: string;

 public constructor(baseURL: string, token?: string) {
   this.baseURL = baseURL;
   this.instance = axios.create({
   baseURL,
 });
 this.token = token;
 this.initializeRequestInterceptor();
}

private initializeRequestInterceptor = () => {
  this.instance.interceptors.request.use(this.handleRequest);
};

private handleRequest = (config: AxiosRequestConfig) => {

  // config.headers!["Authorization"] = `Bearer ${this.token}`;
  config.headers!["Accept-Language"] = "EN";
  config.headers!["X-BingApis-SDK"] = "true";
  config.headers!["X-RapidAPI-Key"] = "secret_key";
  config.headers!["X-RapidAPI-Host"] = "bing-news-search1.p.rapidapi.com";
  return config;
 };
}

step 2:

create the api service class, this class would then extend the abstract class, in the proccess inheriting all methods and fields(if any). in our case, all we require is the Constructor.

import { AxiosBaseService } from "./AxiosBaseService";

export class BingNewsService extends AxiosBaseService {
  private static classInstance?: BingNewsService;

  constructor() {
   super("https://bing-news-search1.p.rapidapi.com");
  }

  public static getInstance() {
    if (!this.classInstance) {
      this.classInstance = new BingNewsService();
     }

     return this.classInstance;
  }

 public bingNewsData = () => {
 this.instance
  .get("/news", {
    params: { cc: "us", safeSearch: "on", textFormat: "Raw" },
  })
  .then((response) => {
    if (response) {
      console.log(response.data);
      return response;
    }
  });
 };
}

step 3

call the api service(BingNewsService) class in your page component(SSR)

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const bingNews = BingNewsService.getInstance();
  const res = bingNews.bingNewsData();
  return {
    props: {
      data: res.data,
    },
  };
};

Notice you might notice we dont have a response interseptor...is to keep things simple.so we focus on the actual problem.

Now you can use axios headers globally. even better, you can always extend the abstract class to configure whatever api service you need use with axios.

alternatively to view your request data and more info do a console.log(res) the data should be in your integrated terminal as the request was done at request so it won't display on the browser console tab.

I hope this help :)