When someone visits a site using Next.js, the redirect feature may successfully load the site, but it fails to actually

I have a serverless logout function in Next.js:

import magic from './magic';
import { withSessionRoute } from './sessions';

export default withSessionRoute(async function logoutHandler(
  request,
  response,
) {
  try {
    if (request.method === 'GET') {
      if (request.session.user) {
        await magic.users.logoutByIssuer(request.session.user.issuer);
      }

      request.session.destroy();

      return response.redirect(302, '/').end();
    }

    const message = 'This endpoint only supports the GET method.';
    return response.status(405).json({ message });
  } catch (error) {
    console.log(error);
  }
});

The key point is

response.redirect(302, '/').end();
.

I trigger this using a button's onClick handler:

const logoutRoute = '/api/logout';

const logoutRequest = () => axios.get(logoutRoute);

async function handleLogoutClick() {
  return await logoutRequest();
}

// ... later

<button onClick={handleLogoutClick}>
  {t('user-authentication:logout')}
</button>

However, after the request is resolved, the browser does not redirect to /.

$ yarn dev
yarn run v1.22.17
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from /Users/janhesters/dev/my-proj/.env.local
event - compiled client and server successfully in 943 ms (217 modules)
wait  - compiling /home (client and server)...
event - compiled client and server successfully in 173 ms (594 modules)
wait  - compiling /api/logout...
event - compiled client and server successfully in 96 ms (612 modules)
wait  - compiling / (client and server)...
event - compiled client and server successfully in 56 ms (620 modules)
wait  - compiling...
event - compiled successfully in 76 ms (58 modules)

https://i.sstatic.net/4KttP.png

What do I need to add so that the frontend actually redirects to /?

Answer №1

According to my specific situation, Router.push was executing successfully.

There was something within getServerSideProps that was triggering an immediate redirect back to the login page.

export const getServerSideProps = withIronSessionSsr(
  async function getServerSideProps({ req, locale }) {
    const user = req.session.user;

    if (!user) {
      return {
        redirect: {
          destination: '/login',
          permanent: false,
        },
      };
    }

    return {
      props: {
        user: mapUserSessionToUserProfile(user),
        ...(await serverSideTranslations(locale, [
          'common',
          'home',
          'user-authentication',
        ])),
      },
    };
  },
  sessionOptions,
);

The issue I am facing is that request.session.user is currently returning as undefined, but that is a separate matter to address.

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

In the upcoming Next.js version 13 and utilizing the App Router, my goal is to retrieve information from an API

Everything on the website is running smoothly, however, there seems to be an issue when clicking on the back button in the browser. For more information, please refer to the screenshots below: Error encountered when clicking on the back button Here is the ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

Breaking up React code within the React.createElement() function

I am encountering an issue with lazily loaded pages or components that need to be rendered after the main page loads. When using createElement(), I receive the following error: LazyExoticComponent | LazyExoticComponent is not assignable to parameter of ty ...

Typescript in React is throwing an error that says you cannot destructure the property 'colored' from the 'boxShadows' object because it is undefined

After downloading the material dashboard react theme from an open source GitHub project, I tried to convert the project into Typescript (React + Typescript). However, I encountered the following error (See Attached Image) https://i.stack.imgur.com/YZKpK.p ...

Having trouble exporting data with getStaticProps in Next.js?

Hello, I am currently working on server side rendering with React and NextJS. My goal is to retrieve some data from an API to display on my home page, but I'm encountering some challenges. One issue I've come across is the error message stating t ...

How can I resolve the problem of transferring retrieved data to a POST form?

When it comes to the form, its purpose is to send data fetched from another API along with an additional note. The fetched data was successfully received, as I confirmed by logging it to the console. It seems that the form is able to send both the fetche ...

What is the best way to invoke a child component function for selective parent components in Next.js?

Recently, a situation arose with a component named child.jsx. This component contains a button that triggers a function called handleClick when clicked. The challenge is that after importing this component into two others - parent1.jsx and parent2.jsx - I ...

Encountering errors while working with React props in typing

In my application, I am utilizing ANT Design and React with 2 components in the mix: //PARENT const Test = () => { const [state, setState] = useState([]); function onChange( pagination: TablePaginationConfig, filters: Record<string, ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

Uploading Files with Angular 2 using AJAX and Multipart Requests

I am currently working with Angular 2 and Spring MVC. At the moment, I have an Upload component that sends an AJAX request to the Spring backend and receives a response containing parsed data from a .csv file. export class UploadComponent { uploadFile: f ...

Resolving conflicts between AbortSignal in node_modules/@types/node/globals.d.ts and node_modules/typescript/lib/lib.dom.d.ts within an Angular project

An issue occurred in the file node_modules/@types/node/globals.d.ts at line 72. The error message is TS2403: Subsequent variable declarations must have the same type. Variable 'AbortSignal' should be of type '{ new (): AbortSignal; prototype ...

Sacrificing type safety versus retaining type safety

I'm curious to know what sets apart these two approaches when declaring the status property. I understand that the second version maintains type safety, but how exactly does it achieve this? export type OwnProps = { id: number; name: string; sta ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

Encountering an issue in Angular 4 AOT Compilation when trying to load a Dynamic Component: Error message states that the

My Angular application is facing challenges when loading dynamic components. Everything works smoothly with the JIT ng serve or ng build compilation. Even with AOT ng serve --prod or ng build --prod, I can still successfully build the application. Lazy loa ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

Unable to exclude specific files using VSCode's "files.exclude" feature

In my workspace settings file, the configuration for excluding certain files is as follows: { "files.exclude": { "**/*.js": { "when": "$(basename).ts" }, "app/**/*.js.map": { "when": "$(basename).ts" ...