-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
34 lines (28 loc) · 1.09 KB
/
middleware.ts
File metadata and controls
34 lines (28 loc) · 1.09 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const authPages = ["/login", "/auth-error"];
function isAuthenticated(request: NextRequest): boolean {
const token = request.cookies.get("authjs.session-token-admin");
return !!token;
}
// TODO: add a rate limiter for api or server-side routes.
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// If the user is authenticated and trying to access an auth page, redirect to dashboard
if (isAuthenticated(req) && authPages.includes(pathname)) {
return NextResponse.redirect(new URL("/", req.url));
}
// If the user is not authenticated and trying to access a protected route, redirect to login
if (
!isAuthenticated(req) &&
!authPages.includes(pathname) &&
!pathname.startsWith("/reset-password/")
) {
return NextResponse.redirect(new URL("/login", req.url));
}
// Otherwise, allow the request to continue
return NextResponse.next();
}
export const config = {
matcher: ["/((?!static|favicon.ico|_next|.*\\..*|api|trpc).*)", "/"],
};