auth0 / nextjs-auth0

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

v4 not exporting AccessTokenError #1819

Open robcaldecott opened 3 days ago

robcaldecott commented 3 days ago

Checklist

Description

In our custom middleware we are checking for an auth0 session token like this:

const accessToken = await auth0.getAccessToken();
if (!accessToken) {
  // Redirect to the auth0 login page
  return NextResponse.redirect(new URL("/auth/login", req.url));
}

However, I think getAccessToken can also throw errors, and if so we want to redirect to login. In this case we would need to handle AccessTokenError so we can do something like this:

try {
  const accessToken = await auth0.getAccessToken();
  ...
} catch (err) {
  if (err instanceof AccessTokenError) {
    console.error(err);
    return NextResponse.redirect(new URL("/auth/login", req.url));
  }
  throw err;
}

However, I cannot find AccessTokenError in the auth0 package.

For now I can instead do this:

try {
  const accessToken = await auth0.getAccessToken();
  ...
} catch (err) {
  if (err instanceof Error && err.name === "AccessTokenError") {
    console.error(err);
    return NextResponse.redirect(new URL("/auth/login", req.url));
  }
  throw err;
}

But I think access to AccessTokenError would be preferred.

Thanks in advance.

Reproduction

See above

Additional context

No response

nextjs-auth0 version

4.0.0-beta.6

Next.js version

15.0.3

Node.js version

20

guabu commented 1 day ago

Hi @robcaldecott 👋 Thanks for the feedback! In the next release (linked above), the AccessTokenError will be thrown when a new token could not be obtained. The error and codes will also be exported under @auth0/nextjs-auth0/errors.