I’m running into a problem in our Next.js WebApp.
In our middleware we retrieve the session using the Auth0Client.getSession() function and then based on some condition we re-authenticate the user using a silent login (by redirecting to /auth/login?prompt=none)
However, I’ve now run into the scenario where getSession() returns a valid session with a user profile etc. but then redirecting to the silent login URL returns an error saying Login required.
Am I wrong to assume that, when getSession() returns a session, there is an active user right now and silent login should be possible and safe?
And if I can assume this, how could it happens that I still get an active session, but cannot silently login my user?
Thank you again @sumansaurav for providing your expertise on the matter and always providing such detailed responses! Glad to have you around the community.
Some follow up, I realize as I’m trying this now that this is the React SDK, but we use the next.js SDK v4. I can find some similar functions there, but not all. I can, for example, not find how you would log someone out only locally. Any chance you might know how this would work in the next.js v4 SDK?
No direct logout() - You need to manually clear cookies or use the logout API endpoint
// In an API route or server action
import { getSession, updateSession } from '@auth0/nextjs-auth0';
// Clear local session without Auth0 logout
export async function clearLocalSession(req, res) {
// Clear the session by setting it to null/undefined
await updateSession(req, res, null);
// Or redirect to clear cookies
res.setHeader('Set-Cookie', [
'appSession=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax',
]);
}
You can use either approach of clearing the session or redirect to clear cookies
Recommended Pattern:
Instead of trying to do silent login, use getAccessToken() which will automatically refresh tokens if possible, or throw an error if the Auth0 session is invalid. This gives you a cleaner way to detect when the Auth0 session has expired even though your local session exists.
Thanks again I’m getting a little confused though, because everywhere in the auth0 next.js examples and even in their own implementation of with-api-auth-required (here) they only ever use getSession() to check if a user is still authenticated. How come it is not necessary to check if the user still has an active session there?