-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
61 lines (54 loc) · 1.5 KB
/
Copy pathmiddleware.ts
File metadata and controls
61 lines (54 loc) · 1.5 KB
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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
const protectedPaths = [
"/dashboard",
"/projects",
"/planner",
"/pomodoro",
"/timers",
"/team",
"/voice",
"/settings",
];
const buildAuthUrl = (request: NextRequest) => {
const apiBase = (process.env.NEXT_PUBLIC_API_BASE || "/api").replace(/\/+$/, "");
if (apiBase.startsWith("http")) {
return `${apiBase}/auth/me`;
}
return `${request.nextUrl.origin}${apiBase}/auth/me`;
};
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const isProtected = protectedPaths.some(
(path) => pathname === path || pathname.startsWith(`${path}/`),
);
const useMocks = process.env.NEXT_PUBLIC_USE_MOCKS === "true";
if (!isProtected || useMocks) return NextResponse.next();
try {
const res = await fetch(buildAuthUrl(request), {
headers: { cookie: request.headers.get("cookie") ?? "" },
cache: "no-store",
});
if (res.ok) {
const data = await res.json();
if (data?.user) return NextResponse.next();
}
} catch {
// silently fall through to redirect
}
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("next", pathname);
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: [
"/dashboard/:path*",
"/projects/:path*",
"/planner/:path*",
"/pomodoro/:path*",
"/timers/:path*",
"/team/:path*",
"/voice/:path*",
"/settings/:path*",
],
};