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 :)