Nextjs + Auth0 + Express

I wrote a middleware to redirect all my api requests (except /api/auth) to my express backend server. This works fine when I run it on my localhost (i.e. nodejs runtime), but gives a 401 (basically no auth token) when I deploy it to vercel (i.e. edge runtime).

import {
  getSession,
  withMiddlewareAuthRequired,
} from "@auth0/nextjs-auth0/edge";
import { NextRequest, NextResponse } from "next/server";
export { getSession };
export default withMiddlewareAuthRequired(async function middleware(
  req: NextRequest
) {
  if (req.nextUrl.pathname.startsWith("/api/auth")) {
    return;
  }
  const res = NextResponse.next();
  const user = await getSession(req, res);
  const token = user?.accessToken;
  if (token) {
    res.headers.set("Authorization", `Bearer ${token}`);
  }
  return res;
});

export const config = {
  matcher: ["/onboarding/:path*", "/api/:path*"],
};

Hi @chinrust,

Welcome to the Auth0 Community!

As you have discovered, the 401 error code happened because your response does not contain an auth token. In this case, you could try using the node.js runtime over the edge runtime to see if that resolves the issue.

Let me know if you continue having issues with this.

Thanks,
Rueben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.