Explore the next page on the API response by navigating to another page

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?

Answer №1

Router functions as a client-side API, not server-side. This means that any routing done on the server-side essentially has no effect. In such cases, you will need to handle the error accordingly.

For client-side implementation, if an error is returned when a function is called, you can redirect the user to a different page.

On the client-side:

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

On the 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Microsoft Edge browser incorrectly calculates range.endOffset value

This particular problem is specific to the Microsoft Edge browser. I am attempting to apply a CSS style to a selected word using Range API's, but I am encountering an issue with the range.endOffset functionality in Edge. Below is the code snippet I am ...

Transmitting JSON AJAX response to populate location markers on Google Maps

When a button is clicked, an AJAX response is triggered to display JSON data based on a search query. My goal is to take the all_locations variable from the AJAX response and use it to show markers on a Google map. I'm uncertain about how to achieve t ...

Content in TinyMCE styled with the default CSS of the application

Hello fellow developers; I'm struggling to find a suitable solution to apply the same styles from our main CSS file to the text entered in the TinyMCE editor. Just to clarify, I don't want to alter the overall theme or appearance of TinyMCE itse ...

Tips for creating successful tests for a project that includes i18n functionality

I have been working on a Next.js project for some time now. The project includes i18n support, and I'm keen to write unit tests for it. However, I've hit a roadblock in figuring out the most effective way to approach writing these tests. Should I ...

Issue with PrimeReact dropdown component not recognizing an array in TypeScript

Trying to incorporate the PrimeReact Dropdown component in a NextJs app with TypeScript. Encountering an error when attempting to select options from the dropdown list: "Objects are not valid as a React child (found: object with keys {name, code})" The b ...

Is it possible to convert a leaflet marker into a nuxt-link function?

Recently, I started using nuxt and vue-leaflet to create an interactive map, even though I am quite new to it. This map consists of multiple markers representing different locations. The goal is for the respective page to open when a user clicks on a mark ...

Refining a JQuery scroll animation using mouseover functionality

I came across a JQuery scroll animation (inspired by this specific answer to a similar question that almost perfectly suited my requirements), and I managed to get it working. My goal is to achieve a side-scroll effect of icons when the user hovers over th ...

Is it possible to use a link's URL as the action for a modal form submission?

I am writing a Rails application that requires users to store credential information in the database... ...

When I click on my Material UI avatar image, it seems to override the button I had in

Every time I try to create a basic category filter with images, I encounter a frustrating bug. After examining the console log, it seems that when I click on the button, my image is being clicked and behaving like an image. However, when I click around the ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

I'm having trouble locating the airtable module, even after I successfully ran npm install airtable

Currently attempting to integrate the airtable api into my website's backend using node.js. However, upon writing var Airtable = require('airtable'); and running the file with node [filepath], I encounter an error in the command prompt: ...

The rendering of HTML is not supported by Next.js SSR

I'm a bit confused about how Next.js SSR works. On my index page, I've used getServerSideProps, so I expected the page to be prerendered as HTML. However, it seems to only render a single div, a JSON object, and the Next.js scripts, with the page ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

Utilizing HTML5's geolocation API to construct a geofence

Is there a way to utilize the HTML5 geolocation API to determine if a user is located in a specific area? I'm considering setting a central latitude and longitude and creating a radius around it, so the site will function as long as the user is within ...

Opt for CSS (or JavaScript) over SMIL for better styling and animation control

I recently noticed an alert in my Chrome console that SVG's SMIL animations are being deprecated and will soon be removed. The message suggested using CSS or Web animations instead. Since I want to transition from SMIL to CSS animations, there are a ...

Tips for storing mustache templates for rendering in Node.js

My data is stored in the following format: let data = {"list" :[ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f9fafb8afef0f9f5e8f4fdb6fbf7f5">[email protected] ...

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

Utilize react-router-dom for conditional rendering based on button clicks

When the user types in "user" in the text box, they will be directed to the user page. If they type "admin", they will be redirected to the admin page. This code belongs to me. constructor(props) { super(props); this.state = { userType : 0 ...

When directly called from index.js, Next.js getStaticProps and getInitialProps return undefined for a component

I've been following this tutorial: https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops, but I decided to create a new component instead of adding the code directly to the index.js file. Although the tutorial's method works fin ...