diff --git a/lib/getBaseUrl.ts b/lib/getBaseUrl.ts new file mode 100644 index 0000000..675f6b1 --- /dev/null +++ b/lib/getBaseUrl.ts @@ -0,0 +1,24 @@ +export function getBaseUrl() { + // 1. If running inside the browser, use relative path "/" + if (typeof window !== "undefined") { + return ""; + } + + // 2. If running on Vercel (deployment) + if (process.env.VERCEL_URL) { + return `https://${process.env.VERCEL_URL}`; + } + + // 3. If running on Appwrite Cloud Production & you set custom domain + if (process.env.NEXT_PUBLIC_APPWRITE_URL) { + try { + const url = new URL(process.env.NEXT_PUBLIC_APPWRITE_URL); + return `${url.origin}`; + } catch (error) { + console.error("Invalid APPWRITE endpoint:", error); + } + } + + // 4. Fallback for Local Development + return `http://localhost:${process.env.PORT ?? 3000}`; +} diff --git a/proxy.ts b/proxy.ts index c2c8609..88aa6b6 100644 --- a/proxy.ts +++ b/proxy.ts @@ -1,4 +1,5 @@ import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"; +import { getBaseUrl } from "@/lib/getBaseUrl"; const isPublicRoute = createRouteMatcher([ "/sign-in(.*)", @@ -9,20 +10,18 @@ const isPublicRoute = createRouteMatcher([ ]); export default clerkMiddleware(async (auth, req) => { - if (!isPublicRoute(req)) { - const baseUrl = - process.env.NODE_ENV === "production" - ? "https://your-domain.com" - : "http://localhost:3000"; - await auth.protect({ unauthenticatedUrl: `${baseUrl}/landing` }); - } + // Allow public routes + if (isPublicRoute(req)) return; + + // Redirect unauthed → /landing + await auth.protect({ + unauthenticatedUrl: `${getBaseUrl()}/landing` + }); }); export const config = { matcher: [ - // Skip Next.js internals and all static files, unless found in search params - "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)", - // Always run for API routes + "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|png|svg|woff2?|ico|csv|zip|webmanifest)).*)", "/(api|trpc)(.*)", ], };