aboutsummaryrefslogtreecommitdiff
path: root/apps/web/middleware.ts
blob: cf53d37e49a414b5e9195ffb6ebb069b1398c42e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { getSessionCookie } from "better-auth/cookies"
import { NextResponse } from "next/server"

export default async function proxy(request: Request) {
	console.debug("[PROXY] === PROXY START ===")
	const url = new URL(request.url)

	console.debug("[PROXY] Path:", url.pathname)
	console.debug("[PROXY] Method:", request.method)

	const sessionCookie = getSessionCookie(request)
	console.debug("[PROXY] Session cookie exists:", !!sessionCookie)

	// Always allow access to login and waitlist pages
	const publicPaths = ["/login", "/login/new"]
	if (publicPaths.includes(url.pathname)) {
		console.debug("[PROXY] Public path, allowing access")
		return NextResponse.next()
	}

	if (url.pathname.startsWith("/api/")) {
		if (!sessionCookie) {
			console.debug("[MIDDLEWARE] API route without session, returning 401")
			return new Response(JSON.stringify({ error: "Unauthorized" }), {
				status: 401,
				headers: { "Content-Type": "application/json" },
			})
		}
		console.debug("[MIDDLEWARE] API route with session, allowing access")
		return NextResponse.next()
	}

	// If no session cookie and not on a public path, redirect to login
	if (!sessionCookie) {
		console.debug(
			"[PROXY] No session cookie and not on public path, redirecting to /login",
		)
		const url = new URL("/login", request.url)
		url.searchParams.set("redirect", request.url)
		return NextResponse.redirect(url)
	}

	// TEMPORARILY DISABLED: Waitlist check
	// if (url.pathname !== "/waitlist") {
	// 	const response = await $fetch("@get/waitlist/status", {
	// 		headers: {
	// 			Authorization: `Bearer ${sessionCookie}`,
	// 		},

	// 	console.debug("[PROXY] Waitlist status:", response.data);
	// 	if (response.data && !response.data.accessGranted) {
	// 		return NextResponse.redirect(new URL("/waitlist", request.url));
	// 	}
	// }

	console.debug("[PROXY] Passing through to next handler")
	console.debug("[PROXY] === PROXY END ===")
	const response = NextResponse.next()
	response.cookies.set({
		name: "last-site-visited",
		value: "https://app.supermemory.ai",
		domain: "supermemory.ai",
	})
	return response
}

export const config = {
	matcher: [
		"/((?!_next/static|_next/image|images|icon.png|monitoring|opengraph-image.png|bg-rectangle.png|onboarding|ingest|login|api/emails).*)",
	],
}