-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
41 lines (32 loc) · 1.06 KB
/
Copy pathmiddleware.ts
File metadata and controls
41 lines (32 loc) · 1.06 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const PUBLIC_ROUTES = ["/signin", "/signup"];
const DEFAULT_AUTH_REDIRECT = "/dashboard";
const DEFAULT_GUEST_REDIRECT = "/signin";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const token = request.cookies.get("access_token");
const isPublic = PUBLIC_ROUTES.some((route) => pathname.startsWith(route));
const isProtected =
pathname.startsWith("/dashboard") ||
pathname.startsWith("/profile") ||
pathname.startsWith("/logout");
if (!token && isProtected) {
return NextResponse.redirect(new URL(DEFAULT_GUEST_REDIRECT, request.url));
}
if (token && isPublic) {
return NextResponse.redirect(new URL(DEFAULT_AUTH_REDIRECT, request.url));
}
if (pathname === "/") {
return NextResponse.redirect(
new URL(
token ? DEFAULT_AUTH_REDIRECT : DEFAULT_GUEST_REDIRECT,
request.url,
),
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/:path*"],
};