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

Trouble with accessing public environment variables in Next.js on Azure Static Web App

My app was originally deployed on Vercel, but I have now decided to switch to Azure because I am integrating Azure AD and using MongoDB on Azure. This move is aimed at reducing networking delays. All of my environment variables are configured under Config ...

Encountering issues with Jest Setup in Next.js as it appears to unexpectedly include a React import in index.test.js

Hey there, I've been pondering over this issue for the past few days. It appears to be a common error with multiple solutions. I'm facing the dreaded: Jest encountered an unexpected token /__tests__/index.test.js:16 import React from "r ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

Error message: "Window is not defined in Next.js"

Can anyone help me with this issue I'm experiencing: 'window is not defined' error? useEffect(() => { const handleScroll = () => { if(typeof window !== 'undefined') { // scrolling dete ...

An easy way to create an input field after clicking a button

When I try to add a field on Button Click, the default field is not showing and does not get added upon button click I have put in my best effort but I cannot figure out what the problem is. I have added functions and used Math to generate a unique id. Th ...

Can anyone tell me the best way to access the name attribute of an HTML element in TypeScript?

Currently, my code is utilizing the name attribute to verify whether the user has entered information in a specific field and validating the input. However, I am facing an issue where the submit button remains active even if there are empty fields presen ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

What is the process for assigning a predefined type that has already been declared in the @types/node package?

Is there a way to replace the any type with NetworkInterfaceInfo[] type in this code snippet? Unfortunately, I am unable to import @types/node because of an issue mentioned here: How to fix "@types/node/index.d.ts is not a module"? Here is the o ...

Tips on accessing a browser cookie in a Next.js API endpoint

I've set a cookie in the layout.js component and it's visible in the browser. Now, I need to be able to retrieve that cookie value when a post request is made to my API and then perform some action based on that value. Despite trying different ...

Steps to align the outline of VS Code with the current location in the editor

When working in a language known for its large and complex files, it can be frustrating to navigate through the code. I often find myself scrolling up and down multiple times just to locate the current function name. This is why I am looking for a way to e ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community, As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy. I currently have three pages with numerous FormGroups that overlap signif ...

Creating a dynamic configuration for service instantiation in Angular 4/5

Currently working on a library that has an AuthModule with an AuthService for managing OAuth2 authentication using oidc-client-js. I want the application using this library to be able to set up the configuration for the OAuth client. One way to do this is ...

Reverse proxies like IIS, Apache, and nginx are capable of forwarding user details that have been authenticated with NTLM to both express.js and

Currently, our organization utilizes Tomcat and Spring/Java for its internal web applications. Through Waffle, Tomcat allows NTLM(SSPI) authenticated user details to be accessed in the Spring/Java application, eliminating the need for users to log in. The ...

Can Envs in Bit be linked together?

My React environment is set up at this link: . It is configured with the following dependencies: { /** * standardize your component dependencies. * @see https://bit.dev/docs/react-env/dependencies **/ "policy": { // peer and dev ...

Retrieve the client's IP address in NextJS utilizing server-side rendering (SSR)

I am currently working on a weather application and I am retrieving the client IP using IPIFY. However, this method results in losing SSR (Server-Side Rendering), or I can use SSR and get the server IP instead. A suggestion was made to me that I could util ...

Issues persist with @typescript-eslint/no-unused-vars not functioning as expected

.eslintrc.json: { "root": true, "ignorePatterns": ["projects/**/*"], "overrides": [ { "files": ["*.ts"], "extends": [ "eslint:recommended", ...

Defining the structure of an object using a type interface

I am having trouble identifying the issue with this type declaration in relation to the interface. When using TypeScript, I encountered an error message stating: "State is an unresolved variable". Does anyone have insights on why this might be considered ...

Converting Amplify project from React to Next.js has hit a snag: The "target" property in next.config.js is no longer supported

I am currently working on migrating a project from React to Next.js in Amplify. Locally, everything runs smoothly but when attempting to enable auto-deploys from the Amplify console, I encountered the following error: Error: The "target" property is no lo ...