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

Logout fails to clear cookies when AUTH0_COOKIE_DOMAIN is set, causing immediate re-authentication

Open getinnocuous opened this issue 1 year ago • 2 comments

Checklist

  • [x] The issue can be reproduced in the nextjs-auth0 sample app (or N/A).
  • [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.

Description

Describe the problem

When AUTH0_COOKIE_DOMAIN is set to enable cross-subdomain authentication (required for API calls), the logout process fails to properly clear Auth0 cookies from the parent domain, causing users to be immediately re-authenticated after logout.

What was the expected behavior?

Logout should clear all Auth0 cookies regardless of the cookie domain setting, preventing automatic re-authentication.

Configuration:

export const auth0 = new Auth0Client({
  authorizationParameters: {
    scope: env.AUTH0_SCOPE,
    audience: env.AUTH0_AUDIENCE,
    redirect_uri: `${URL}auth/callback`,
  },
  secret: env.AUTH0_SECRET,
  domain: env.AUTH0_DOMAIN,
  appBaseUrl: URL, // https://localhost.mydomain.com:3000/
  clientId: env.AUTH0_CLIENT_ID,
  clientSecret: env.AUTH0_CLIENT_SECRET,
})
AUTH0_COOKIE_DOMAIN="df.mydomain.com"  # Required for API authentication
AUTH0_DOMAIN="auth.mydomain.com"
AUTH0_BASE_URL="https://localhost.df.mydomain.com:3000/"

Reproduction

Steps:

  1. User logs in successfully
  2. Cookies are set on domain df.mydomain.com (as expected)
  3. User navigates to /auth/logout
  4. Logout redirects to Auth0 and completes successfully
  5. User is redirected back to application at https://localhost.df.mydomain.com:3000/
  6. BUG: User is immediately re-authenticated because cookies on parent domain weren't cleared

Domain Structure:

  • App runs on: https://localhost.df.mydomain.com:3000/
  • Cookie domain: df.mydomain.com (parent domain, required for API calls)
  • Auth0 domain: auth.mydomain.com

Workaround: Commenting out AUTH0_COOKIE_DOMAIN fixes logout but breaks API authentication.

Additional context

Middleware setup

import { type NextRequest, NextResponse } from 'next/server'
import { auth0 } from './lib/auth0'
import { ACCESS_TOKEN_COOKIE_NAME } from '@/constant/server'
import { env } from '@/env.mjs'

function setAccessTokenCookieOnResponse(
  response: NextResponse,
  accessToken: string,
) {
  response.cookies.set({
    name: ACCESS_TOKEN_COOKIE_NAME,
    domain: env.AUTH0_COOKIE_DOMAIN,
    value: accessToken,
    path: '/',
    sameSite: 'lax',
    httpOnly: true,
    secure: true,
  })
  return response
}

function handleLoginReturnToUrl(request: NextRequest) {
  const returnTo = `${request.nextUrl.basePath}${request.nextUrl.pathname}`
  const loginUrl = new URL(`/auth/login`, request.url)
  loginUrl.searchParams.set('returnTo', returnTo)
  console.log({ loginUrl })
  return loginUrl
}

function accessTokenCookie(token: string) {
  return `${ACCESS_TOKEN_COOKIE_NAME}=${token}; Domain=${env.AUTH0_COOKIE_DOMAIN}; Path=/; SameSite=Lax; HttpOnly; Secure;`
}

const publicRoutes = new Set(['/', '/playground', '/playground/explore'])

export async function middleware(request: NextRequest) {
  const response = await auth0.middleware(request)

  // Ensure middleware does not handle the `/auth` routes, auto-mounted and handled by the SDK
  if (request.nextUrl.pathname.startsWith('/auth')) {
    return response
  }

  if (publicRoutes.has(request.nextUrl.pathname)) {
    return response
  }

  // Any route that gets to this point will be considered a protected route, and require the user to be logged-in to be able to access it
  const session = await auth0.getSession(request)

  if (!session) {
    return NextResponse.redirect(handleLoginReturnToUrl(request))
  }

  const { token: accessToken, expiresAt = 0 } = await auth0.getAccessToken(
    request,
    response,
  )

  const accessTokenExpiryDate = expiresAt * 1000 // convert the time from seconds to milliseconds
  const tokenHasExpired = accessTokenExpiryDate <= Date.now()

  if (tokenHasExpired) {
    try {
      const refreshedToken = await auth0.getAccessToken(request, response, {
        refresh: true,
      })
      return setAccessTokenCookieOnResponse(response, refreshedToken.token)
    } catch {
      return NextResponse.redirect(handleLoginReturnToUrl(request))
    }
  }

  return setAccessTokenCookieOnResponse(response, accessToken)
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file) + PWA icons
     * - api/public (public api routes)
     */
    '/((?!api/public|ingest|_next/static|_next/image|favicon-16x16.png|favicon-32x32.png|android-chrome-192x192.png|android-chrome-512x512.png|apple-touch-icon.png|favicon.ico|mstile-150x150.png|site.webmanifest|browserconfig.xml|auth-error).*)',
  ],
}

export default middleware

nextjs-auth0 version

^4.8.0

Next.js version

15.3.4

Node.js version

v22.14.0

getinnocuous avatar Jul 18 '25 07:07 getinnocuous

I am having the same issue.

asleroid avatar Jul 18 '25 16:07 asleroid

Same issue here.

I have two apps running: a.example.com and b.example.com so I set the cookie domain to .example.com. When I try to logout from a.example.com the set cookie does not include the custom domain.

set-cookie session=; Path=/; Max-Age=0

So the session persists.

maurodaprotis avatar Jul 22 '25 15:07 maurodaprotis