-
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) · 875 Bytes
/
middleware.ts
File metadata and controls
34 lines (28 loc) · 875 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
34
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
const authenticatedRoutes: Array<string> = [
'/players',
'/players/[id]',
]
const unauthenticatedRoutes = [
'/login',
'/register'
]
export default async function middleware(req: NextRequest) {
// Get the pathname of the request (e.g. /, /protected)
const path = req.nextUrl.pathname;
// If it's the root path, just render it
if (path === "/") {
return NextResponse.next();
}
const session = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
if (!session && authenticatedRoutes.includes(path)) {
return NextResponse.redirect(new URL("/login", req.url));
} else if (session && unauthenticatedRoutes.includes(path)) {
return NextResponse.redirect(new URL("/players", req.url));
}
return NextResponse.next();
}