Encountering a Next.js redirect issue with 'The page is not redirecting properly' in _app.js

I'm currently working on the user authentication section of a nextjs app. The majority of it is done, except for the protected routes. I'm trying to manage the authentication aspect in _app.js. Below is the code snippet:

import App from 'next/app'
import '../styles/globals.css'
import { parseCookies } from 'nookies'
import { redirectUser } from '../utils/auth'
import jwt from 'jsonwebtoken'

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    const { token } = parseCookies(ctx)
    
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    if (!token) {
      const isProtectedRoute = ctx.pathname === '/account'
      if (isProtectedRoute) {
        redirectUser(ctx, '/login')
      }
    } else {
      try {
        const verified = jwt.verify(token, process.env.JWT_SECRET)
      } catch(err) {
        console.error(err)
        redirectUser(ctx, '/login')
      }
    }
    
    return { pageProps }
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Component {...pageProps} />
    )
  }
}

export default MyApp

Here is my redirectUser file:

import cookie from 'js-cookie';
import Router from 'next/router';

export function handleLogin(token) {
    cookie.set('token', token)
    Router.push('/account');
}

export function redirectUser(ctx, location) {
    if (ctx.req) {
        ctx.res.writeHead(302, { Location: location })
        ctx.res.end()
    } else {
        Router.push(location)
    }
}

The authentication part correctly redirects when a user doesn't have a token. However, if the token is tampered with and becomes invalid, a redirect error occurs:

The page isn’t redirecting properly

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

I've identified that the second redirectUser call causes this issue. Even placing it outside the else statement at the end of the getInitialProps function yields the same result.

Answer №1

There seems to be an issue causing an infinite redirect loop to the /login page.

Whenever a page with an invalid token is accessed, it automatically redirects to the /login page. This triggers another call to App.getInitialProps, leading to yet another redirect to the /login page due to the persistent invalid token, creating a cycle.

To prevent this behavior, you can implement checks specifically for the /login page within your code. Here's an example:

if (!token) {
    const isProtectedRoute = ctx.pathname === '/account'
    if (isProtectedRoute) {
        redirectUser(ctx, '/login')
    }
} else if (ctx.pathname !== "/login") { // To avoid redirect loop
    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET)
    } catch(err) {
        console.error(err)
        redirectUser(ctx, '/login')
    }
}

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

Is there a way to showcase a Matplotlib graph using FastAPI/Nextjs without needing to save the chart on the local machine

For my website, I am utilizing a Nextjs frontend along with a FastAPI backend. On the frontend, there is an input form for capturing an 'ethereum address'. Using this address, a matplotlib chart displaying 'ethereum balance over time' i ...

When searching through a MySQL stored procedure using Node.js, a null row is returned if no records are found by the

In my NodeJS application, I am using the MySQL library to call a stored procedure in MySQL. However, when the stored procedure does not return any matching records, the library returns an object with key values set to null. The following is the Stored Pro ...

Building interactive chat "hubs" with Node, Express, Heroku, and Socket.io

As I've been working on my app for a while now, scalability issues have started to arise. With my limited experience in Node and Heroku, I'm reaching out for some guidance. Initially, I followed this tutorial to set up my node service, essential ...

The redirection feature in nodejs/expressjs does not seem to function properly

I attempted to use the redirect function in expressjs to serve a webpage, but for some reason it's not functioning properly. I must be missing something here. index.html: <html> <body> <div id="clicked"> not clicked </div&g ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Node-Sass Errors Occurring During Docker Compose Up Build

Every time I attempt to construct my docker container using the docker-compose up --build command, a multitude of errors surfaces. The reoccurring issues with node-sass and node-gyp persist despite exhaustive searches for solutions. System Specs MacOS 11 ...

Issue with Mongoose not triggering .pre('save') function when using bcrypt

Struggling to develop a straightforward Authentication app and encountering an obstacle with the .pre('save') middleware not activating when attempting to store the hashed password in Mongodb. Here is my version of the Model.js File. import mong ...

Issue with establishing socket connection between React and Express.js

When setting up the socket in app.js(backend), I follow this approach: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser&apos ...

Utilizing Node.js ORM2 callback functions with custom parameters

Currently, I am developing models using a for loop: for (var j = 0; j < data.length; j++) { models.MyModel1.create({ name : data[j].name }, function(err, model){ if (err) { throw err } ...

Steps for dynamically loading mui icons from mui with TypeScript

Is it possible to dynamically load MUI icons based on a string parameter using the following code snippet? import Icon from "@mui/icons-material" import SvgIcon from '@mui/material/SvgIcon'; const IconComponent = (props: typeof SvgIco ...

Adding additional parameters to route handlers in Express

I'm new to using Express and I'm interested in finding a way to increase the reusability of routes. In my application, I anticipate having numerous routes that can be handled by a common function but with different templates. For example: app.g ...

encountering a 404 error when trying to access a route with a parameter in Express 4

Having issues while attempting to use a param in a route. I referred to the 4.x documentation on the Express website but still facing a 404 error. It seems like my function is not being triggered. The other routes for creating and listing all items are wo ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Encountering a timeout exceeded error when running Mocha tests

My experience with Mocha testing has presented an interesting challenge when running server.test.js 1) "before each" hook for "should get all todos": Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if re ...

Issue with adding a key:value pair to res.locals.object in Node/Express not functioning as expected

Currently, I am working on constructing an object within res.locals by executing multiple MongoDB operations and utilizing the next() middleware. Once I have added an object to res.locals, such as: res.locals.newObject, my goal is to subsequently add addi ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

Encountered an issue while trying to install tailwindcss-elevation

Currently, I am facing dependency issues while attempting to install multiple npm packages in my main test_project directory. Here is a breakdown of the steps I took before encountering errors: npm init -y npm install -D tailwindcss@latest postcss@lates ...

Sass issue: extending compound selectors is no longer supported

Encountered an error in my React app while running npm start. Using node version: v14.17.6 and npm version: 6.14.9 Error message: Failed to compile. Issue found in ./src/index.scss file with the following error: SassError: compound selectors may no long ...

Gathering every import within a single file

Is it a good practice to centralize all import files in an allExports.js file and then call them whenever needed from there? My main goal is to have visibility and control over all files from one place... It seems pretty neat and makes the code clear, but ...