How to handle access decline gracefully with @auth0/nextjs-auth0?

Hello everyone,

I have setup the auth0 handler in my NextJS app according to GitHub - auth0/nextjs-auth0: Next.js SDK for signing in with Auth0

The thing that is bothering me is that if a user declines to authorize the app on Auth0, they get bounced back to my /callback endpoint which is wrapped with withPageAuthRequired(Component) which then errors out the following

Server Error

BadRequestError: access_denied (User did not authorize the request)

<small>This error happened while generating the page. Any console logs will be displayed in the terminal window.</small>

So I wonder if there’s anything I can do so that I can handle this more gracefully? Do I need to remove the withPageAuthRequired(Component) wrapper? I would rather keep it so that route is only available for signed in users.

Is redirecting them back to the root route if they chose to deny access a possibility?

Steps to reproduce:

  • Have a /callback route that is wrapped with withPageAuthRequired() function which comes with the @auth0/nextjs-auth0 library
  • Log in to an account with your tenant and make sure you’re asking for: 1.Profile access and 2. Allow offline access
  • Click Decline
  • Get redirected to the /callback route

Thanks!

1 Like

Ha! Fixed it!

For anyone interested:

In your [...auth0].js file you need to add custom callback handling like so:

const authOptions = {
  async callback(req, res) {
    try {
      await handleCallback(req, res, { afterCallback })
    } catch (error) {
      console.log(error)
      res.status(error.status || 500).end(error.message)
    }
  },
}

export default handleAuth(authOptions)

The magic sauce is happening in the catch block where it will handle the denial of service correctly. For me I will handle it by login out the user and sending it to the root route.

Thanks to anyone that looked at this!

Thank you @mishchief for sharing your solution with us! :+1: :clap:

1 Like