DEV Community

Ferdynand Odhiambo
Ferdynand Odhiambo

Posted on

Leveraging Axios Interceptors in Next.js

🌟 Introduction

In modern web applications, managing API requests efficiently is crucial for delivering a seamless user experience. One of the most effective ways to handle this in a Next.js application is by using Axios interceptors. This article will guide you through implementing request interceptors in Axios to manage authentication tokens, ensuring secure communication with your backend. Let's dive in! πŸŽ‰

πŸ€” What are Axios Interceptors?

Axios interceptors are functions that Axios calls for every request or response. They allow you to modify requests or responses before they are handled by then or catch. This feature is particularly useful for:

  • πŸ”‘ Adding authentication tokens

  • πŸ“œ Logging requests

  • ⚠️ Handling errors globally

πŸ› οΈ Setting Up Axios in Next.js

To get started, you need to install Axios in your Next.js project. Open your terminal and run:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Next, create an Axios instance with a base URL for your API. This instance will be used throughout your application for making API calls.

import axios from 'axios';

const api = axios.create({ baseURL: 'http://localhost:8080' });
Enter fullscreen mode Exit fullscreen mode

✨ Implementing Request Interceptors

Now, let’s implement a request interceptor to automatically attach an authentication token to every request. This is how you can do it:

api.interceptors.request.use(
  (config) => {
    if (typeof window !== "undefined") {
      const token = localStorage.getItem("token");
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    }
    return config;
  },
  (error) => Promise.reject(error)
);
Enter fullscreen mode Exit fullscreen mode

πŸ“– Explanation:

  • The interceptor checks if the code is running in the browser (to avoid issues during server-side rendering).

  • It retrieves the token from localStorage and adds it to the Authorization header of the request if it exists.

  • If there’s an error in the request configuration, it is rejected.

🎯 Benefits of Using Interceptors

  • Centralized Logic: By managing authentication in one place, you reduce redundancy and improve maintainability. This means you can easily update your authentication logic without having to change multiple files. πŸ› οΈ

  • Error Handling: You can intercept responses to handle errors globally. For example, if a token is expired, you can redirect users to the login page or refresh the token automatically. πŸ”„

  • Cleaner Code: Your API calls remain clean and focused on their primary purpose without repetitive token management. This leads to better readability and maintainability of your code. πŸ“š

πŸ“¦ Example Usage

Here’s how you can use the configured Axios instance in your Next.js components:

import api from './path/to/your/api';

const fetchData = async () => {
  try {
    const response = await api.get('/data-endpoint');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};
Enter fullscreen mode Exit fullscreen mode

In this example, the fetchData function makes a GET request to the specified endpoint. The interceptor ensures that the authentication token is included in the request headers automatically. πŸŽ‰

🏁 Conclusion

Using Axios interceptors in your Next.js applications can significantly enhance your API interaction strategy. By automating the process of attaching authentication tokens, you can focus more on building features rather than managing boilerplate code.

If you have any questions or want to share your experiences with Axios and Next.js, feel free to reach out! Let's connect and share knowledge! πŸ’¬ Happy coding! 🎈

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.