-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.route.ts
35 lines (29 loc) · 925 Bytes
/
middleware.route.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
import { verifyToken } from "@/lib/server/auth";
import { type NextRequest, NextResponse } from "next/server";
const allowedRoutes = [
"/api/auth/signin",
"/api/auth/signup",
"/api/auth/reset-password",
"/api/auth/change-password",
];
export async function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
if (!allowedRoutes.includes(pathname)) {
// validate the user is authenticated
const verifiedToken = await verifyToken(req);
if (!verifiedToken) {
if (pathname.startsWith("/api/")) {
return new NextResponse(
JSON.stringify({ error: { message: "authentication required" } }),
{ status: 401 }
);
} else {
return NextResponse.redirect(new URL("/auth/signin", req.url));
}
}
}
return NextResponse.rewrite(new URL(req.url));
}
export const config = {
matcher: ["/api/:path*", "/protected/:path*"],
};