-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
34 lines (27 loc) · 1001 Bytes
/
middleware.ts
File metadata and controls
34 lines (27 loc) · 1001 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 { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose'; // Use jose instead of jsonwebtoken
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Protect /admin routes
if (pathname.startsWith('/admin')) {
// Get the token from cookies
console.log('Admin route detected');
const token = req.cookies.get('token')?.value;
if (!token) {
return NextResponse.redirect(new URL('/auth', req.url));
}
try {
// Use jose library instead of jsonwebtoken
const secret = new TextEncoder().encode('very-secret-key');
await jwtVerify(token, secret);
return NextResponse.next();
} catch {
return NextResponse.redirect(new URL('/auth', req.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/admin', '/admin/:path*'],
};