I have one function called postAPI which is common function to send any request to back end server in my next app.
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 postAPI function can be called from any next component as required.
I am trying to redirect user to login page whenever API returns 401 status code.
I am using next/router
but it is not redirecting to home page. It will clear cookies and local storage but Router.push
does not redirect to home page.
Any idea what am I doing wrong here?