withMiddlewareAuthRequired() not redirecting to custom login route (Next.js)

import { withMiddlewareAuthRequired, getSession } from "@auth0/nextjs-auth0/edge";
import { NextRequest, NextResponse } from "next/server";

export default withMiddlewareAuthRequired(async function middleware(req: NextRequest) {
    const res = NextResponse.next();
    const session = await getSession(req, res);

    if (!session) {
        // Redirect user to the login API route if not authenticated
        return NextResponse.redirect(new URL("/api/v1/auth/login", req.url));
    }

    return res;
});

export const config = {
    matcher: ["/topics/:path*", "/chats/:path*", "/profile", "/settings", "/home"],
};

Whenever the session expires, I am always redirected to the following URL instead of ‘/api/v1/auth/login’:

{baseURL}/api/auth/login?returnTo=%2Fchats

I’ve tried a bunch of different workarounds, but nothing works.

Any ideas of how to fix this?

Hi @solarpathic

Welcome to the Auth0 Community!

Please try the following when redirecting the user:

return NextResponse.redirect(`${baseURL}/api/v1/auth/login`, req.url);

or

return NextResponse.redirect(process.env.loginURL, req.url);

Otherwise, if the user is redirected to the /login?, are they able to authenticate through that page or not?

Let me know if this helps.

Kind Regards,
Nik

That doesn’t work as it goes right back to ‘/api/auth/login’.

That line is synonymous with what I already have.

‘/login?’ doesn’t work because my API routing is setup as ‘/api/v1/auth/login’, not ‘/api/auth/login’.

I suppose I could just make my auth have the path of ‘/api/auth/’ instead of ‘/api/v1/auth’, but I would like to keep the auth in the v1 directory.

Hi @solarpathic

I am not quite sure why it redirects to a different path then the one declared in the redirect. Perhaps, somewhere in your implementation the API routing is not set up correctly or your logic overrides the one you set up.

I would recommend to visit the following pages since they might help you in doublechecking your implementation:

If by any chance the information above was helpful, feel free to leave a reply to let us know!
In the meantime, I will be investing the matter as well and come back with an update as soon as possible.

Kind Regards,
Nik