-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
34 lines (26 loc) · 988 Bytes
/
middleware.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
// CREDIT: https://github.com/vercel/nextjs-postgres-auth-starter/blob/main/middleware.ts
import { getToken } from 'next-auth/jwt';
import { NextRequest, NextResponse } from 'next/server';
const rootPath = '/';
const loginPath = '/';
const authorizedPath = '/protected';
async function middleware(req: NextRequest) {
const reqPath = req.nextUrl.pathname;
if (reqPath === rootPath) {
// If it's the root path, render the page.
return NextResponse.next();
}
const session = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
if (!session && reqPath === authorizedPath) {
// If not logged in and not in protected path, go to login page.
return NextResponse.redirect(new URL(loginPath, req.url));
} else if (session && reqPath === rootPath) {
// If logged in and in root path, go to protected page.
return NextResponse.redirect(new URL(authorizedPath, req.url));
}
return NextResponse.next();
}
export default middleware;