Unhandled rejection error occurred when attempting to redirect to a different page in Next.js version 13, resulting in a NEXT_REDIRECT error

Currently, I'm attempting to validate whether a user is logged in and if not, redirect them to the login page.

Here's the code snippet I am using:

import { onAuthStateChanged } from 'firebase/auth'
import { auth } from '../src/firebaseConfig'
import { redirect } from 'next/navigation'

// ...

export default async function Home() {
  onAuthStateChanged(auth, (user) => {
    if (!user) {
      redirect('/login')
    }
  })
  // ...

However, I encounter an error with this code:

error - node_modules/next/dist/client/components/redirect.js (47:18) @ getRedirectError
error - unhandledRejection: Error: NEXT_REDIRECT
    at getRedirectError (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:40:19)
    at redirect (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:46:11)
    at eval (webpack-internal:///(sc_server)/./app/layout.tsx:29:70)
    at eval (webpack-internal:///(sc_server)/./node_modules/@firebase/auth/dist/node-esm/totp-e47c784e.js:2684:26) {
  digest: 'NEXT_REDIRECT;replace;/login'
}

In another branch where I haven't yet implemented authentication checking, I have similar code in the same location which works perfectly fine.

import { redirect } from "next/navigation";

export default function Home() {
  redirect("/home");
}

What am I missing or doing incorrectly in my initial code?

Answer №1

It is important to avoid invoking the redirect function within the generateMetadata method of the page.

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

Angular - Bootstrap modal displays as a standalone element rather than a dialog box

Currently working on my initial Angular project, I am attempting to incorporate a dialog that prompts for confirmation before deleting an item. Utilizing ng-bootstrap, I referred to the examples in the documentation as my starting reference. The issue I a ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

While utilizing Typescript, it is unable to identify changes made to a property by a

Here is a snippet of code I am working with: class A { constructor(private num: number = 1) { } private changeNum() { this.num = Math.random(); } private fn() { if(this.num == 1) { this.changeNum(); if(this.num == 0.5) { ...

In the realm of Next.js 13.4 API streaming, tokens make their way to localhost in a staggered fashion, whereas in a production environment

Issue Encountered with API Streaming Behavior in Next.js 13.4 An unexpected issue has arisen with the API streaming functionality in Next.js 13.4 when using the app router, specifically related to the behavior of tokens being sent all at once instead of i ...

Comparing Necessary and Deduced Generic Types in TypeScript

Can you explain the difference between these two generic types? type FnWithRequiredParam<T> = (t: T) => void type FnWithParamInferred = <T>(t: T) => void From what I understand, FnWithRequiredParam will always require the generic type t ...

One developer session using MongoDB with NextJS/Vercel leads to the formation of numerous connections that continue to grow exponentially

I have a Next.js app deployed on Vercel, with MongoDB connected in the Next.js api folder. Despite running just one dev session with minimal usage, the number of connections in MongoDB keeps increasing and often goes past 300 connections. I'm curious ...

Integrating Next.js with a authentication provider and a Redux provider

During the development of my Next js project, I incorporated Next auth using import {Provider} from 'next-auth/client' to wrap the <Component /> in _app.js. However, I also want to integrate Redux into the project. This involves importing ...

Anyone have any suggestions on how to resolve the issue with vertical tabs in material UI while using react.js?

I'm working on integrating a vertical tab using material UI in react.js, but I'm facing an issue where the tabs are not appearing. Here is the snippet of my code: Javascript: const [value, setValue] = useState(0); const handleChange1 = (event ...

Deliver a numerical input to the component on an equivalent hierarchical tier

I need to find a way to pass the values of the "things" array to another component on the same level in my app. The structure of my app is as follows: sidebar.component data.service body.component In the sidebar component, I have a button that triggers a ...

Acquire request data prior to exiting function in React

I am working on a NextJS application that utilizes axios for making requests to a backend API, which requires an authentication token. To handle this, I have implemented a function that retrieves the auth token and stores it in a variable at the module-lev ...

Switching between PascalCase and camelCase in TypeScript leads to unexpected behavior

Currently, I am in the process of transitioning a C# desktop application to an Angular/TypeScript web application. In the C# application, all class properties are named using PascalCase. Therefore, I decided to maintain this naming convention in the TypeS ...

Emphasize a Row Based on a Certain Criteria

One of the challenges I am facing is how to emphasize a specific row in a table based on certain conditions. Currently, I am utilizing Jqxgrid and have made some modifications in the front-end to achieve the highlighting effect: TypeScript: carsDataAgain ...

When the page reloads, the firebase currentUser variable is found to be

Currently utilizing Firebase for authentication. Prior to making a request to the backend, I always ensure to request the idToken. service.interceptors.request.use(async request => { const token = await firebase.auth().currentUser.getIdToken(); i ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

Learn how to dynamically activate an icon in Angular to enhance user interaction

HTML Code: The Zoom Component <div class="zoom py-3"> <i nz-icon nzType="minus" (click)="zoomToggle(false)" nzTheme="outline"></i><br> <i nz-icon nzType="plus" (click)=&q ...

Determine if a specific route path exists within the URL in Angular

http://localhost:4200/dsc-ui/#message but if I change the URL to (remove #message and type application-management) http://localhost:4200/dsc-ui/application-management (/application-management), it should automatically redirect me to http://localhost:4200/d ...

If the user clicks outside of the navigation menu, the menu is intended to close automatically, but unfortunately it

I have a nav file and a contextnav file. I've added code to the nav file to close the navigation when clicking outside of it, but it's not working. How can I ensure that the open navigation closes when clicking outside of it? Both files are in ts ...

Webpack: The command 'webpack' does not exist as a recognized cmdlet, function, script file, or executable program

Attempting to set up a new project using webpack and typescript, I have created the project along with the webpack file. Following the instructions on the webpack website, I successfully installed webpack using npm install webpack webpack-cli --save-dev ...

Images are not loading in NextJs image component on a Digital Ocean deployed application

I recently encountered an issue with my NextJs project. While using the NextJs Image Component for images, everything worked perfectly fine when running locally. However, after deploying the project on Digital Ocean, all the images served through the Next- ...

Checking the parameters passed to a function in Typescript: A step-by-step guide

Currently, I am working with Typescript and then transpiling my TS code into JavaScript. However, I have encountered an issue that I am struggling to resolve. The error message I am facing is as follows: Error Found in TypeScript on Line:2 - error TS230 ...