Tiếng Việt

Improving the security of the website's API with the Interceptor feature in Axios.

Share

inter.png

Hi everyone, my name is Tuyen and I'm currently a Front-end intern at ABC Software Solutions. During the process of studying and working here, I was able to participate in a small project that gave me the opportunity to interact with many new technologies from the company. And what makes me excited when doing the project is learning more knowledge and skills about the front-end (FE), a little bit about the back-end (BE) along with the ability to think about teamwork. together. Regarding the project I'm working on, the technology used is mainly TypeScript, JavaScript, Scss (FE) and NestJS (BE). NestJS will make a RESTful API to bridge the NextJS web application to work smoothly with the relational database PostgresSQL. By building API call methods such as GET, POST, PUT, PATCH through specific API paths with the help of Axios library, the API can effectively communicate with applications (FE) like React. , NextJS, Vue,…. To optimize the API call method when the browser sends a request to BE and BE returns a result instead of using too many different APIs in Axios, we use an optimal solution. better than Interceptor Axios. To better understand how it works and its uses. Let's explore some of the following concepts together.

JavaScript

JavaScript (JS) is an interpreted programming language developed from the concept of prototypes. It is the most commonly used programming language today. This language is widely used for web pages (user side) and also server side (with Node.JS).
js.jpeg

TypeScript

TypeScript is a code language open source. It is a strict superset of JavaScript and adds an optional static type feature to the language. TypeScript is designed to develop large applications and convert to JS. TS.jpeg

NextJS

Next.js is a framework React front-end is developed as open-source adding optimization capabilities such as server-side rendering and static website generation. next.png

NestJS

NestJS is a Node. JS allows building server-side applications. It is an open source framework that uses TypeScript and is very flexible to build BE systems. NestJS.png

RESTfulAPI and Axios

  • RESTful API is a standard used in the design of APIs for web applications to manage resources.
  • Axios is an HTTP client written on top of Promises (asynchronous handling) that supports defining API applications and can be used in browsers and nodes. configurable default features, error handling, request cancellation, serialization of JavaScript objects to JSON automatically. Also, generate XMLHttpRequests from the browser, make HTTP requests from node.js and it can intercept requests and responses. Is a flexible and powerful solution to perform HTTP requests (request, response between FE, BE).

Interceptor Axios

Interceptor axios is a function used to call all Axios requests. Called to update/transform each request before forwarding it and check/filter the response before returning it, append headers as Bearer Tokens, or change the request/response params. In short, you can intercept requests or responses before they are processed in BE, similar to middleware. Since calling API is asynchronous processing in TypeScript, we need to use Promise and end Combined with the then() functions to handle when the API call is successful or .catch() when the API returns some error, interceptors have a feature that allows the application to intercept invalid requests or responses such as not logged in or the account is not authorized to access some restricted API. To access data, every HTTP request needs a header to verify that the request sent to the server is valid (authenticated) and to allow access to those particular APIs (User Account Authorization). Sometimes the HTTP response returned is an error response status of 400 or higher. At those times, you may want to automatically retry the request or verify that the denied authorization is still valid. http-status-codes.png Some features it brings: Decentralize a properly authenticated account to access those APIs. Prefix all requests with hostname (Add content to header. Log all requests and responses Set a generic error Resend request if it fails In projects with languages JavaScript/TypeScript users often use Interceptor axios as middleware for header validation or sending requests and responses to applications. To use axios for making API requests we need to install it in our project.

Here is the command to run in Terminal:

npm install axios

Or if you use yarn to run it:

yarn add axios

Once the installation is complete import it into your project:

import axios from 'axios' ;

Basic axios setup with interceptor:

Step 1: Initialize an API connection object

// Add a response interceptor
axios.interceptors.response.use(function (response) {
   // Do something with response data
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});
  • Elements:
  • BaseURL: if you specify a base URL, it will be attached to whatever relative URL you use.
  • Timeout: Set the time to wait for the server to respond to any request. Header: An object of key/value pairs that can be sent in the request header.

Step 2: Create interceptor request with interceptor:

// Add a response interceptor
axios.interceptors.response.use(function (response) {
   // Do something with response data
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});

You use axios.interceptors.request.use() to modify the request before it is triggered.

Step 3: Create response interceptor with interceptor:

// Add a response interceptor
// Add a response interceptor
axios.interceptors.response.use(function (response) {
   // Do something with response data
  return response ;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});

Use axios.interceptors.response.use() to process the response before it is returned to the end-user web application.

This is all the knowledge I have learned about Interceptor Axios. Thank you for reading up to here. Reference links at: https://axios-http.com/docs/interceptors and https://rapidapi.com/guides/http-interceptors-axios

Share

Contact Us