-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmiddleware.ts
34 lines (28 loc) · 984 Bytes
/
middleware.ts
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
import { betterFetch } from "@better-fetch/fetch";
import { Session } from "better-auth";
import { NextResponse, type NextRequest } from "next/server";
export default async function authMiddleware(request: NextRequest) {
const isAuthPage =
request.nextUrl.pathname.startsWith("/login") ||
request.nextUrl.pathname.startsWith("/signup");
const isAppPage = request.nextUrl.pathname.startsWith("/app/");
const { data: session } = await betterFetch<Session>(
"/api/auth/get-session",
{
baseURL: request.nextUrl.origin,
headers: {
cookie: request.headers.get("cookie") || "",
},
},
);
if (session && isAuthPage) {
return NextResponse.redirect(new URL("/app/home", request.url));
}
if (!session && isAppPage) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/app/:path*", "/login", "/signup", "/signup/sent", "/login/sent"],
};