nextjs-auth0 icon indicating copy to clipboard operation
nextjs-auth0 copied to clipboard

v4: Customize auth handlers

Open mvvmm opened this issue 11 months ago • 8 comments

Checklist

  • [x] I have looked into the Readme, Examples, and FAQ and have not found a suitable solution or answer.
  • [x] I have looked into the API documentation and have not found a suitable solution or answer.
  • [x] I have searched the issues and have not found a suitable solution or answer.
  • [x] I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • [x] I agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

In v3, we could customize the auth handlers in /api/auth/[auth0] via something like:

export const GET = handleAuth({
  async logout(req: NextApiRequest, res: NextApiResponse) {

   // do custom stuff

   return await handleLogout(req, res);
  },
});

Reference:

I'm not finding that something similar exists in v4.

Describe the ideal solution

Ability to customize the auth handlers in v4.

The handleLogout() helper is an important piece of this. We need the ability to write our own custom code and then rely on the default auth handler as a fallback, or in addition to our custom code.

Alternatives and current workarounds

Depends on the use case, but as far as I can tell, there is no way to run custom code in the middle of those new auth handlers, /auth/logout, for example.

Additional context

No response

mvvmm avatar Feb 10 '25 20:02 mvvmm

+1'ing this request here. As an aside, if you are simply looking to update session post /auth/callback, you may want to look at the beforeSessionSaved and onCallback hooks. These ended up fitting my usecase ok here for the moment. https://github.com/auth0/nextjs-auth0/blob/47e45ee9ea46b4670fed2566a9caa17b2d6fbc02/EXAMPLES.md#hooks

priley86 avatar Mar 03 '25 22:03 priley86

It's also not taking the basePath from next.config.

maninderpreetsingh avatar Mar 06 '25 22:03 maninderpreetsingh

@maninderpreetsingh - yes that appears to be the root of this issue, the logic here that is: https://github.com/auth0/nextjs-auth0/blob/main/src/server/auth-client.ts#L225-L250

As a heads up to maintainers, this issue (which was recently fixed) is closely related and should be tested alongside w/ any changes for this callback customization. It seems after those changes are applied currently though, the APP_BASE_URL is respected as far as request path goes.

priley86 avatar Mar 07 '25 15:03 priley86

Has there been updates or resolution to this? I'm also not seeing anywhere how to replace the current handles in version 4

srowe0091 avatar Mar 17 '25 18:03 srowe0091

We need the ability to customize auth handlers. And the ability to set and modify cookies We have an existing logic that doesn't work with this upgrade.

logout: async (req: NextApiRequest, res: NextApiResponse) => { const url = new URL(req.url ?? ''); let redirectPage = url.searchParams.get('redirect_url') ?? ''; const returnTo = /${redirectPage}; try { const cookieStore = cookies(); cookieStore.set('silentLoginAttempFailed', 'true', { maxAge: 30 }); cookieStore.delete('trpat'); cookieStore.delete('trponeat'); return await handleLogout(req, res, { returnTo: returnTo, }); } catch { // do nothing } },

Please bring back this ability.

aviralnx avatar Apr 28 '25 14:04 aviralnx

👋 Hi, apologies for the late reply to this issue. To run custom code before auth handlers in V4, you can intercept the corresponding request in the nextjs middleware as follows:

export async function middleware(request) {

    // prepare NextResponse object from auth0 middleware
    const authRes = await auth0.middleware(request);

    // intercept logout call
    if (request.nextUrl.pathname === "/auth/logout") {
        // do custom stuff
        console.log("Pre-logout code")

        // Example: Set a cookie
        authRes.cookies.set('myCustomCookie', 'cookieValue', { path: '/' });
        // Example: Set another cookie with options
        authRes.cookies.set({
            name: 'anotherCookie',
            value: 'anotherValue',
            httpOnly: true,
            path: '/',
        });

        // Example: Delete a cookie
        // authRes.cookies.delete('cookieNameToDelete');

        // you can also do an early return here with your own NextResponse object
        // return NextResponse.redirect(new URL('/custom-logout-page'));
    }

    // return the original auth0-handled NextResponse object
    return authRes
}

Similarly, you can intercept other auth routes like:

  • /auth/login : intercept call before login
  • {your login returnTo url} : intercept call after login, see here
  • /auth/callback : intercept call before callback
  • The onCallback hook : run code after callback has happened
  • {your logout returnTo url} : intercept call after logout, see here

Hope this was helpful, if not please provide us more info about your detailed use-case and we can discuss how we can provide a solution for you. Thanks!

tusharpandey13 avatar Jun 03 '25 13:06 tusharpandey13

if this is the intended approach and not a hack of some sort then this should be documented somewhere and would mark this issue closed once the docs says this is the replacement for the previous behavior

srowe0091 avatar Jun 04 '25 13:06 srowe0091

if this is the intended approach and not a hack of some sort then this should be documented somewhere and would mark this issue closed once the docs says this is the replacement for the previous behavior

+1

aviralnx avatar Jun 04 '25 13:06 aviralnx

Hi 👋 @srowe0091 @aviralnx Thank you for your inputs on this, #2218 is open to add docs for customizing auth handlers. Will be merged soon.

tusharpandey13 avatar Jul 16 '25 12:07 tusharpandey13