Skip to content

Commit efbadb5

Browse files
Add proxy specific handler
1 parent 1e35679 commit efbadb5

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

src/server/auth-client.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,42 @@ export class AuthClient {
413413
}
414414
}
415415

416+
/**
417+
* Proxy handler that routes to the appropriate proxy handler method
418+
* @param nextRequest The incoming NextRequest instance.
419+
* @returns A Promise that resolves to a NextResponse or undefined.
420+
*/
421+
async proxyHandler(
422+
nextRequest: NextRequest,
423+
): Promise<NextResponse | void> {
424+
// Convert the incomming request to Auth0Request
425+
const auth0Req = new Auth0NextRequest(nextRequest as NextRequest);
426+
// Convert the incoming response to Auth0Response
427+
const auth0Res = new Auth0NextResponse(new NextResponse());
428+
429+
let { pathname } = auth0Req.getUrl();
430+
431+
// Next.js does NOT automatically strip basePath from pathname in middleware.
432+
// We must manually strip it to match against our route configurations.
433+
// Example: With basePath='/app', a request to '/app/auth/login' will have
434+
// pathname='/app/auth/login', but routes are configured as '/auth/login'.
435+
const basePath =
436+
"nextUrl" in nextRequest ? nextRequest.nextUrl.basePath : "";
437+
if (basePath && pathname.startsWith(basePath)) {
438+
pathname = pathname.slice(basePath.length) || "/";
439+
}
440+
441+
const sanitizedPathname = removeTrailingSlash(pathname);
442+
443+
if (sanitizedPathname.startsWith("/me/")) {
444+
return this.#unwrapHandler(() =>
445+
this.handleMyAccount(auth0Req, auth0Res)
446+
);
447+
} else if (sanitizedPathname.startsWith("/my-org/")) {
448+
return this.#unwrapHandler(() => this.handleMyOrg(auth0Req, auth0Res));
449+
}
450+
}
451+
416452
/**
417453
* Request handler that routes to the appropriate auth handler method
418454
* @param nextRequest The incoming NextRequest instance.

src/server/client.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,15 @@ export class Auth0Client {
580580
}
581581
}
582582

583+
/**
584+
* Mounts the SDK proxy routes to run as a proxy function.
585+
*/
586+
async proxy(req: NextRequest) {
587+
return await this.authClient.proxyHandler(
588+
toNextRequest(req as NextRequest | Request)
589+
);
590+
}
591+
583592
/**
584593
* getSession returns the session data for the current request.
585594
*

0 commit comments

Comments
 (0)