diff --git a/src/modules/auth.ts b/src/modules/auth.ts index 0736da2..aed6df0 100644 --- a/src/modules/auth.ts +++ b/src/modules/auth.ts @@ -43,15 +43,33 @@ export function createAuthModule( ); } + const hostname = window.location.hostname; + const isPreview = hostname.startsWith("preview--"); + + // Skip redirect if already on login page (but not on preview - preview should redirect to main app) + if (window.location.pathname === "/login" && !isPreview) { + return; + } + // If nextUrl is not provided, use the current URL const redirectUrl = nextUrl ? new URL(nextUrl, window.location.origin).toString() : window.location.href; + // For preview URLs (preview--*), redirect to main app's login page + // but keep from_url pointing to the preview URL + let loginBaseUrl = options.appBaseUrl ?? ""; + if (isPreview) { + const mainHostname = hostname.replace(/^preview--/, ""); + loginBaseUrl = `${window.location.protocol}//${mainHostname}${ + window.location.port ? ":" + window.location.port : "" + }`; + } + // Build the login URL - const loginUrl = `${ - options.appBaseUrl ?? "" - }/login?from_url=${encodeURIComponent(redirectUrl)}`; + const loginUrl = `${loginBaseUrl}/login?from_url=${encodeURIComponent( + redirectUrl + )}`; // Redirect to the login page window.location.href = loginUrl;