Logging out completely

Hey,

I’ve seen a range of folk raising logout-doesn’t-really-logout, I’d like to try again. Failing this I will raise a ticket on the nextjs-auth0 Github project.

I don’t consider my implementation anything other than standard, that is to say:

  • Login button with href /api/auth/login?returnTo=/dashboard
  • Out of the box middleware.ts for protecting /dashboard/*
  • A logout button with href /api/auth/logout

If I click my Login button, I’ll go to the Auth0 universal login, and get redirected to my /dashboard page, with all the user hooks working. Excellent. I can see a cookie called appSession.

If I click logout, I get taken back to my / login page. I can see the appSession cookie is removed.

BUT

If I tap login, to go to /api/auth/login?returnTo=/dashboard then I am automatically logged into /dashboard, without the Auth0 universal login.

This is challenging, because I am trying to test with many users in development, so I need to be able to properly logout. It’s also IMO a security risk if this happens in production, as if I want to logout my session, someone in a coffee shop should not be able to tap login and expect to be logged in.

One thing that DOES work is overwriting the /api/auth/[auth0]/route.ts as follows:

import { handleAuth, handleLogout } from "@auth0/nextjs-auth0";
import { NextResponse } from "next/server";

// export const GET = handleAuth();

export const GET = handleAuth({
  logout: async (req, res) => {
    return NextResponse.redirect(
      process.env.AUTH0_LOGOUT_OIDC +
        "?post_logout_redirect_uri=" +
        encodeURIComponent(process.env.AUTH0_BASE_URL)
    );
  },
});

This follows the info at Use the OIDC Endpoint to Log Users Out of Auth0, except:

  • The final logged out screen has no way for the user to get back to the original site loging page
  • The post_logout_redirect_uri is ignored, despite being described as operational at Use the OIDC Endpoint to Log Users Out of Auth0 and despite my adding it to both Tenant Settings, and my Application Settings - in the allowable Logout URL fields

My questions are:

  1. How are others logging out users using the auth0-nextjs library?
  2. Are others finding that login is not always requires despite calling logout?
  3. Are others using this OIDC approach to logging out at the identity provider side and if so, does post_logout_redirect work?
2 Likes

I’ve encountered similar logout issues. Many resort to OIDC logout, but it can be inconsistent. Post-logout redirect sometimes doesn’t work as expected. Looking for insights and best practices from others.

Hey all - for me, I got this fixed by going into my Dashboard > Advanced > Log In Session Management and changed it to nonpersistent and 1 minute each for the other values. Then waiting after logging out for 2 min before clicking login again.

Hey - that’s not the most usable solution though, as a non-persistent cookie will be removed on closing the browser, requiring a re-login if I close the tab/browser session.

Also, the cookie isn’t the issue here - as I mentioned, the cookie is removed with the /api/auth/logout call, the issue is that some other magic is logging the user back in without logging in if its within a time period of the logout.

For me, logout should mean logout, I don’t understand how this behaviour is useful or secure.

Hence needing this nuisance of needing to use the OIDC logout - suggesting something about the auth0-nextjs library is checking with Auth0 to see if the user is “logged in at the identity side” which needs to be something we can opt out of.

1 Like

I figured out a solution to this. Here’s what I did.

The reason this isn’t working is because the Auth0 NextJS handleLogout just deletes the cookie set on your AUTH0_BASE_URL, but it doesn’t delete the cookie on your AUTH0_ISSUER_BASE_URL, so when you login after logging out, it redirects to that issuer url, sees a valid auth cookie and signs you right back in.

What I found is Auth0 has a /v2/logout endpoint that deletes the cookie from the issuer url, so if you redirect to that endpoint after the handleLogout it will also remove the cookie from your AUTH0_ISSUER_BASE_URL. Here’s my implementation.

/api/auth/[auth0]/route.ts

import { handleAuth, handleLogin, handleLogout } from '@auth0/nextjs-auth0';

const logoutUrl = [
  `${process.env.AUTH0_ISSUER_BASE_URL}/v2/logout?`,
  `client_id=${process.env.AUTH0_CLIENT_ID}`,
  `&returnTo=${process.env.AUTH0_BASE_URL}`,
];

export const GET = handleAuth({
  logout: handleLogout({ returnTo: logoutUrl.join('') }),
});
6 Likes

Thanks it worked for me as well can you please share how you handle token in next js ?

Hey Muhammad, can you be more specific?

Hi Dalton,
Sadly, it didn’t work for me. The appSession cookie keep being added when reloading the page. Even when I send the site to other people, they can see my account logged in.

I found the issue is only client side userinfo updated, the server side session never deleted so it keeps login or keep previous logged in user info in ssr page and api. But I dont know how to solve this

1 Like

import { handleLogout } from ‘@auth0/nextjs-auth0’;

export default async function logout(req, res) {
try {
await handleLogout(req, res, {
returnTo: ‘http://localhost:3000/login
});
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}
This code is not working at all please help me Sir please please

This is working fine for me

// app/src/app/api/auth/[auth0]/route.ts

import { handleAuth, handleLogout } from '@auth0/nextjs-auth0'

export const GET = handleAuth({
  logout: handleLogout({ returnTo: 'http://localhost:3000/api/auth/login' }),
})

You need to define logout url which you pass in returnTo in Auth0 dashboard like http://localhost:3000/api/auth/login

when I wrote the same code it is redirecting to
tenant_auth_domain/v2/logout?returnTo=http://localhost:3000/api/auth/login&client_id=1234 as 404 URL same code i wrote friend.

I experienced the same problem: users can log out normally, but are directly logged in when clicking the login button without the Auth0 universal login. I believe I finally found another solution without having to call the /v2/logout endpoint, although I am not sure as to why it works and if this will also help others out there. In my NextJs project (with App Router) all the Auth0 calls (login, logout etc) were based on the <Link> component (next/link). Changing it to a native <a> tag worked for me without having to customize /api/auth/[auth0]/route.ts

Change

import Link from "next/link";

<Link href="/api/auth/logout">Logout</Link>

to

<a href="/api/auth/logout">Logout</a>

An alternative is doing a force push using the router, as highlighted here. For example, using a <button> component:

import { useRouter } from 'next/navigation';

export default function LogoutButton() {

   const router = useRouter();

   return <button onClick={() => router.push("/api/auth/logout")}>Logout</button>

}
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.