In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server.
import Router from 'next/router';
export const postAPI = async (
endpoint,
data = {},
headers = {},
method = 'POST',
options = {}
) => {
const axios = require('axios');
const { parseCookies } = require('nookies');
const cookies = parseCookies();
const token = cookies[process.env.SESSION_TOKEN_NAME] || false;
const config = {
url: endpoint,
method,
data: data,
headers: {
authorization: headers.authorization
? headers.authorization
: `Bearer ${token}`,
},
...options,
};
const res = await axios(config).catch((err) => {
if (err.response.status === 401) {
Data.logoutUser();
setCookie(null, process.env.SESSION_TOKEN_NAME, null, {
maxAge: 1,
path: '/',
});
deleteAllCookies();
Router.push('/');
window.localStorage.clear();
}
});
return res?.data || res?.err;
};
This handy postAPI function can be easily utilized in any next component as needed.
Whenever the API responds with a 401 status code, I aim to redirect the user to the login page.
Although I am using next/router, the expected redirection to the home page is not happening. The cookies and local storage are cleared, but the Router.push method does not redirect to the home page.
Any suggestions on what might be going wrong in this scenario?