-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
47 lines (40 loc) · 1.22 KB
/
Copy pathmiddleware.ts
File metadata and controls
47 lines (40 loc) · 1.22 KB
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
import { NextRequest, NextResponse } from 'next/server';
import { verifySessionTokenEdge } from '@/lib/auth-edge';
const PUBLIC_PATHS = ['/login'];
export async function middleware(req: NextRequest) {
const { pathname, search } = req.nextUrl;
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/favicon.ico') ||
pathname.startsWith('/public') ||
pathname.startsWith('/api')
) {
return NextResponse.next();
}
const isPublic = PUBLIC_PATHS.some(path => pathname === path || pathname.startsWith(`${path}/`));
if (isPublic) {
return NextResponse.next();
}
const token = req.cookies.get('stacker_auth')?.value;
const session = await verifySessionTokenEdge(token, process.env.AUTH_SECRET);
if (session) {
return NextResponse.next();
}
const url = req.nextUrl.clone();
url.pathname = '/login';
url.searchParams.set('next', `${pathname}${search}`);
const response = NextResponse.redirect(url);
if (token) {
response.cookies.set('stacker_auth', '', {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
path: '/',
maxAge: 0,
});
}
return response;
}
export const config = {
matcher: ['/((?!.*\\..*).*)'],
};