Drashti Kheni
Drashti Kheni

Reputation: 1140

Navigate to other page on API response in next

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?

Upvotes: 0

Views: 1533

Answers (1)

Lázaro Souza
Lázaro Souza

Reputation: 41

Router is a client-side api, not server side, that means any router did on server side basically do nothing. You have to return the error.

When you call this function on client-side and it return an error, you can redirect the user.

client-side

useEFfect(() => {
  async function post() {
    try {
      await postApi();
    } catch (e) {
      console.log(e);
      if (e.response.status === 401) router.push("/home");
    }
  }
  post();
},[])

server-side

export async function getServerSideProps(context) {
  try {
   await postApi();
  } catch (e) {
    console.log(e);
    if (e.response.status === 401) {
      return {
        redirect: {
          permanent: false,
          destination: "/",
        },
      };
    }
  }
}

https://nextjs.org/docs/api-reference/next/router

Upvotes: 2

Related Questions