forked from leerob/next-saas-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
48 lines (40 loc) · 1.33 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { signToken, verifyToken } from '@/lib/auth/session';
const protectedRoutes = '/dashboard';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const sessionCookie = request.cookies.get('session');
const isProtectedRoute = pathname.startsWith(protectedRoutes);
if (isProtectedRoute && !sessionCookie) {
return NextResponse.redirect(new URL('/sign-in', request.url));
}
let res = NextResponse.next();
if (sessionCookie) {
try {
const parsed = await verifyToken(sessionCookie.value);
const expiresInOneDay = new Date(Date.now() + 24 * 60 * 60 * 1000);
res.cookies.set({
name: 'session',
value: await signToken({
...parsed,
expires: expiresInOneDay.toISOString(),
}),
httpOnly: true,
secure: true,
sameSite: 'lax',
expires: expiresInOneDay,
});
} catch (error) {
console.error('Error updating session:', error);
res.cookies.delete('session');
if (isProtectedRoute) {
return NextResponse.redirect(new URL('/sign-in', request.url));
}
}
}
return res;
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};