-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
46 lines (42 loc) · 1.38 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { auth } from "@/auth";
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /_static (inside /public)
* 4. all root files inside /public (e.g. /favicon.ico)
*/
"/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)",
],
};
const unprotectedRoutes = ["/login"];
const protectedRoutes = ["/api", "/bookmarks"];
export default async function middleware(request: NextRequest) {
const session = await auth();
const isUnprotectedRoute = unprotectedRoutes.some((prefix) =>
request.nextUrl.pathname.startsWith(prefix)
);
if (isUnprotectedRoute || request.nextUrl.pathname === "/") {
if (
session &&
(request.nextUrl.pathname === "/" ||
request.nextUrl.pathname === "/login")
) {
const absoluteURL = new URL("/bookmarks", request.nextUrl.origin);
return NextResponse.redirect(absoluteURL.toString());
}
return NextResponse.next();
}
const isProtectedRoute = protectedRoutes.some((prefix) =>
request.nextUrl.pathname.startsWith(prefix)
);
if (!session && isProtectedRoute) {
const absoluteURL = new URL("/login", request.nextUrl.origin);
return NextResponse.redirect(absoluteURL.toString());
}
return NextResponse.next();
}