#`withAuth` only runs if the user is

1 messages · Page 1 of 1 (latest)

hexed kernel
dense cedarBOT
#

Hi @hexed kernel. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

hexed kernel
#

Is there no way around that to have logic run when not authorized? and then if authorized I can run the logic again?

dense cedarBOT
#

Sorry @hexed kernel, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

celest dagger
hexed kernel
#

Not sure I understand? I think that is my question, how to have a regular middleware but at the same time a middleware for withAuth

celest dagger
hexed kernel
#

Oh damn I did not know that, thanks that's perfect ⭐

hexed kernel
#

It seems like that does not work, when exporting a middleware + default export for withAuth it only takes into account the middleware export, small reroduction

export const middleware: NextMiddleware = async (request) => {
  const res = NextResponse.next();
  console.log(">>>>>>>>>> unauthorized middleware <<<<<<<<<<<<<<<<<<<")
  return res;
};

export default withAuth({
  callbacks: {
    authorized: ({ token }) => {
      console.log(">>>>>>>>>> authorized middleware <<<<<<<<<<<<<<<<<<<")
      return false;
    },
  },
});

The only log I receive is from middleware, when I comment it out, it logs the authorized callback

hexed kernel
#

I ended up doing this via a hacky method 🤷‍♂️

export async function middleware(request: NextRequest, event: NextFetchEvent) {
  const res = NextResponse.next();

  console.log('// handle my unauthenticated middlware here');

  const isNotAuthenticated = await withAuth({
    callbacks: {
      authorized: ({ token }) => {
        if (!token) {
          return false;
        }

        if (!token?.idToken) {
          return false;
        }

        if (!verifyTokenSync(token.idToken as string)) {
          return false;
        }

        return true;
      },
    },
    // @ts-ignore
  })(request, event);

  if (isNotAuthenticated) {
    const authUrl = new URL(paths.auth.login, request.nextUrl.origin);
    return NextResponse.redirect(authUrl.toString());
  }

  return res;
}