-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
29 lines (24 loc) · 782 Bytes
/
Copy pathmiddleware.ts
File metadata and controls
29 lines (24 loc) · 782 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import jwt from 'jsonwebtoken'
export async function middleware(req: NextRequest) {
const token = req.headers.get('authorization')?.split(' ')[1]
// Si no es endpoint protegido, dejar pasar
if (!req.nextUrl.pathname.startsWith('/api/')) {
return NextResponse.next()
}
// Si no hay token
if (!token) {
return NextResponse.json({ error: 'Acceso no autorizado' }, { status: 401 });
}
try {
jwt.verify(token, process.env.JWT_SECRET!)
return NextResponse.next();
} catch {
return NextResponse.json({ error: 'Token inválido o expirado' }, { status: 403 });
}
}
export const config = {
// protege todas las rutas de /api
matcher: ['/api/:path*'],
}