-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
33 lines (26 loc) · 939 Bytes
/
Copy pathmiddleware.ts
File metadata and controls
33 lines (26 loc) · 939 Bytes
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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import {getCurrentUser} from "@/lib/session";
export async function middleware(request: NextRequest, response: NextResponse) {
const session = request.cookies.get("session");
//Return to /login if don't have a session
if (!session) {
return NextResponse.redirect(new URL("/login", request.url));
}
const apiEndpoint = new URL("/api/user", `http://${request.headers.host}`);
//Call the authentication endpoint
const responseAPI = await fetch("http://localhost:3000/api/user", {
headers: {
Cookie: `session=${session?.value}`,
},
});
//Return to /login if token is not authorized
if (responseAPI.status !== 200) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
//Add your protected routes
export const config = {
matcher: ["/dashboard/:path*"],
};