auth0 / nextjs-auth0

Next.js SDK for signing in with Auth0
MIT License
2.07k stars 392 forks source link

v4.0.0-beta.7 - when /profile request returns 401 (Unauthhorized) should be handle somehow #1817

Open sleitor opened 1 day ago

sleitor commented 1 day ago

Checklist

Description

Heed some hook, ability, or automatically catch 401 error on /profile (that request by use-user.js on 15th line) to force logout from the app.

How we can catch it and redirect to /login or /logout page?

Reproduction

1) login on auth0 2) in the developer tab remove the cookie 3) focus off/on on the page or just wait couple time 4) after get atomatically on middleware will get a 401 for profile

Additional context

No response

nextjs-auth0 version

v4.0.0-beta.7

Next.js version

15.0.3

Node.js version

v20.18.0

guabu commented 16 hours ago

Hey @sleitor 👋 When the call to /profile returns the 401 the user will no longer be defined. You should be able to check the existence of the user (it will be null if they're not authenticated) and act on that:

"use client";

import { useUser } from "@auth0/nextjs-auth0";

export default function Profile() {
  const { user, isLoading } = useUser();

  if (!user) {
    // handle the logic you want here
  }

  return (
    // ...
  );
}
sleitor commented 14 hours ago

Thank you @guabu! Appreciate for fast answer. that partially works :)

...
  const { user, ...rest } = useUser();
  console.log('rest parameters', rest);
...

There found another bug. when we remove the __session from cookies then In the useUser hook not catched properly 401 responce from fetch

I expecting to see there error like 'Unauthorized' instead "error parsing json" :)

image