乐闻世界logo
搜索文章和话题

How to use an Axios interceptor with Next- Auth

1个答案

1

When developing applications with Next.js, Next-Auth provides a straightforward method for handling authentication. Axios is a widely used HTTP client, and its interceptor functionality enables processing requests before and after they are sent, which is particularly useful for managing authentication tokens.

Using Axios Interceptors to Handle Next-Auth Tokens

1. Install Necessary Dependencies

First, ensure your project has installed next-auth and axios.

bash
npm install next-auth axios

2. Configure Next-Auth

Ensure Next-Auth is correctly set up in your Next.js project. Typically, this involves configuring various options in pages/api/auth/[...nextauth].js, such as providers and databases.

javascript
import NextAuth from "next-auth" import Providers from "next-auth/providers" export default NextAuth({ providers: [ Providers.GitHub({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }), // Other providers ], // Other configurations })

3. Create an Axios Instance and Configure Interceptors

In your project, create a unified Axios instance and configure interceptors. The key is to retrieve the token from Next-Auth's session and attach it to the Authorization header of each request.

javascript
import axios from 'axios' import { getSession } from 'next-auth/client' const axiosInstance = axios.create({ baseURL: 'https://api.example.com', // Other configurations }); axiosInstance.interceptors.request.use(async config => { const session = await getSession(); const token = session?.accessToken; if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); }); export default axiosInstance;

4. Use the Axios Instance for API Requests

Now, every time you send a request using this Axios instance, it automatically adds the Authorization header (if the user is authenticated and the session contains a token).

javascript
import axiosInstance from './path/to/axiosInstance' const fetchData = async () => { try { const response = await axiosInstance.get('/data'); return response.data; } catch (error) { console.error('Error fetching data: ', error); return null; } }

5. Handle Token Expiration or Errors

You can also add logic in the response interceptor to handle token expiration or other API errors.

javascript
axiosInstance.interceptors.response.use(response => { return response; }, async error => { if (error.response.status === 401) { // Handle token expiration, for example by refreshing the token or redirecting to the login page } return Promise.reject(error); });

Conclusion

By implementing this approach, managing HTTP requests in the Next-Auth environment using Axios interceptors becomes simple and efficient. It not only maintains clean and organized code but also effectively manages user authentication states, particularly when automatically handling token addition and expiration during API interactions.

2024年8月5日 11:14 回复

你的答案