forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks.

Let's consider a simpler example where I want to redirect the user to /email-verification if the user.email_verified value is false.

const afterCallback = async (req: any, session: any, state: any) => {
    // const router = useRouter()
    const res = new NextResponse()
    if (session.user) {
        // check email verification status
        if (!session.user.email_verified) {
            return Response.redirect(
                "http://localhost:3000/auth/email-verification",
                308 // test value
            )
        } else {
            // Handling redirection with multi-level if-else blocks
      }
      return session

export const GET = handleAuth({
    login: handleLogin({
        returnTo: "/",
    }),
    callback: async (req: any, res: any) => {
        const callback = await handleCallback(req, res, { afterCallback })
        console.log("callback", callback)
        return callback;
    },
})

Despite setting the redirect status code to 308, I always end up redirected to http://localhost:3000 without user data. Checking the callback constant reveals that its status is actually 302 instead of 308 as intended.

Answer №1

Based on the documentation for the Auth0 SDK.

// app/api/auth/[auth0]/route.js
import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
import { redirect } from 'next/navigation';

const afterCallback = (req, session, state) => {
  if (session.user.isAdmin) {
    return session;
  } else {
    redirect('/unauthorized');
  }
};

export default handleAuth({
  callback: handleCallback({ afterCallback })
});

Encountering an issue with the SDK code: Callback handler failed. REASON: NEXT_REDIRECT.

Various attempts were made to make afterCallback and handleCallback work with redirection while maintaining session data. In the handleCallback, accessing the session using getSession was not successful.

Suggestion is to utilize the page router instead.

//pages/api/auth/[...auth0].ts
const afterCallback = (req, res) => {
  if (!session.user.email_verified) {
    return session;
  } else {
    res.setHeader('location', '/verified');
  }
};

export default handleAuth({
    async callback(req: NextApiRequest, res: NextApiResponse) {
        try {
            await handleCallback(req, res, { afterCallback});
        } catch (error) {
            console.log(error);
            res.redirect('/');
        }
    },
});

Additionally, it has been observed that the handleCallback call lacks support for backward navigation. It is advisable to include a try-catch block as shown in your own code and redirect in case of errors to prevent users encountering a blank screen or error message during backward navigation.

Answer №2

Consider updating state.returnTo instead.

import type { NextRequest } from 'next/server'
import { handleAuth, handleCallback, Session } from '@auth0/nextjs-auth0'

export const GET = handleAuth({
    callback: handleCallback({
        afterCallback(req: NextRequest, session: Session, state: any) {
            state.returnTo = '/newredirectpage'
            return session
        }
    })
})

It is suggested that Auth0 enhance both the quality of their library and customer support services.

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

Guide on deploying a web application using Socket.io and SvelteKit on Vercel

Currently, I'm developing a multiplayer .io-style game that utilizes both Socket.io and SvelteKit. While testing the project on a local development server, everything runs smoothly. However, upon deploying to Vercel, an error message stating Failed to ...

The timezone plugin in day.js may sometimes generate an incorrect date

For a while, I've been using dayjs in my angular project to convert timestamps from UTC to localtime. However, after my recent update, this functionality stopped working. This isn't the first issue I've encountered with dayjs, so I decided t ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

There is no property called 'x' in type 'y'

Can anyone explain why TypeScript is telling me this: Property 'dateTime' does not exist on type 'SSRPageProps'.ts(2339) Looking at my code below, I have data-time typed. import React from "react"; import axios from "axi ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...

Using Typescript generics to create parameter and argument flexibility for both classes and

I'm facing an issue where I need to effectively chain multiple function calls and ensure that TypeScript verifies the correctness of their linkage. export class A<T, K> { public foo(a: A<K, T>): A<K, T> { return a; } } cons ...

Implementing MemberStack for user authentication within a Next.js application by leveraging the functionalities of NextAuth.js

In my current Next.js app with NextAuth.js, I am utilizing MemberStack for authentication. While it may not have been my top choice of tools initially, I am transitioning from a Webflow site that already uses MemberStack for auth. The new site I'm bui ...

Dealing with a nested object problem in Angular using TypeScript

I am currently working on an Angular 15 application that is designed to showcase information about different games to users. Within the application, I have a global object structured like this: GAMES_INFO: { skyroads: { name: 'Sky Roads&a ...

Unable to retrieve external images in NextJS when using a Custom Express server

I'm currently working on a NextJS application with a custom ExpressJS server, but I'm facing an issue where the app is unable to display external images. Below is a snippet of the code: export function DocumentSection({content}) { return ( ...

Customize Next Js styling based on the user's browser requirements

There's a curious issue when viewing my website through Facebook or LinkedIn - the background color suddenly changes to a vibrant green, but only in those particular webviews. However, when I view it through other apps like Twitter or Instagram, the ...

What is the best approach to retrieve and showcase data from a Strapi API using useState in React?

I have a task to retrieve and display the titles, prices, descriptions, and allergies from the Strapi API located at http://localhost:1337/api/pizzasarpsborgs. Link to API However, I'm uncertain how to handle the response data. Can anyone provide gu ...

TypeScript/Javascript - Error: The specified function is not callable

After recently delving into TypeScript, I found myself encountering an error in my code for a wheel mini-game on my app. The specific error being displayed in the console is: this.easeOut is not a function The relevant portion of the code causing the iss ...

Ways to populate missing cells with a default hyphen symbol

Looking for a way to default empty cells in my primeng datatable to '-'. Consider the following data: [ { 'column': null }, { 'column': { 'name': 'A' } }, { 'column': { 'name': ...

Enhance Vue TypeScript components with custom component-level properties

In my vue2 project, I am utilizing vue-class-component along with vue-property-decorator. My goal is to implement component-level security validation for each component when it loads. I imagine implementing it with a signature like this: @Component @Secur ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

Customizing MUI Themes with TypeScript: How do I inform TypeScript that the theme is provided by the provider?

Below is a modified demo code snippet extracted from Material UI documentation: function ThemeUsage() { const theme = { palette: { primary: { main: "#000", }, }, } as const; type DefaultThemeType = { theme: type ...

It appears that Jest is having trouble comprehending the concept of "import type"

We've just completed a major update to our monorepository, bringing it up to date with the following versions: Nx 14.3.6 Angular 14.0.3 Jest 28.1.1 TypeScript 4.7.4 Although the compilation process went smoothly after the upgrade, we encountered num ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...