Authorize user with organization name provided by subsomain

I am trying to implement the following login flow on a Nextjs app with Auth0:

(Assume that organizations and users are already defined)

  1. User access org1.domain.com
  2. The app register org1 then immediatly redirect user to Auth0 Universal Login UI with organization already registered, user now only has to provide email and password
  3. If successfully authenticated, redirect user to domain.com/org1

So far, I have implemented:

  1. Created app/[subdomain]/page.tsx
  2. Toggled on “Allow Organization name in Authorization API” in auth0 settings and chose Business login as well as “No prompt” login
  3. Add these URL in Allowed callback URL:

http://localhost:3002/api/auth/callback, http://{organization_name}.localhost:3002, http://localhost:3002/*

  1. Add middleware to handle requests
middleware.ts

import { NextRequest, NextResponse } from 'next/server';
import {getAccessToken} from "@auth0/nextjs-auth0";


export default function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const hostHeader = req.headers.get('host');
  const orgName = hostHeader.split('.')[0];

  // If on root and there exist a subdomain (e.g abc.domain.com)
  if (pathname === '/' && orgName !== '') {

    // Redirect the user to Auth0 authorization URL with organization as a query param
    const auth0Url = new URL(`${process.env.AUTH0_ISSUER_BASE_URL}/authorize`);
    auth0Url.searchParams.append('client_id', `${process.env.AUTH0_CLIENT_ID}`);
    auth0Url.searchParams.append('response_type', 'code');
    auth0Url.searchParams.append('redirect_uri', `http://localhost:3002/${orgName}`);
    auth0Url.searchParams.append('scope', 'openid profile email');
    auth0Url.searchParams.append('organization', `${orgName}`); // Optional: dynamically set this

    return NextResponse.redirect(auth0Url.toString());
  }

  return NextResponse.next();
}

When I access org1.localhost:3002, it says

The provided redirect_uri is not in the list of allowed callback URLs.

I also tried redirect uri as http://localhost:3002/api/auth/callback but it gave HTTP 400 error instead.

What did I do wrong? Thank you.

Update: it turns out localhost:3002/* is not allowed in Allowed Calback URLs so I explicitly add http://localhost:3002/org1. After that the login UI appeared, after login, it redirected to localhost:3002/org1 but it seems like there are no authentication, useUser returned null and I can’t see appSession in the cookies. Please help.