-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
71 lines (61 loc) · 1.97 KB
/
middleware.ts
File metadata and controls
71 lines (61 loc) · 1.97 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Skip middleware for static files, next.js internals, and public API routes
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/api/auth') ||
pathname.startsWith('/static') ||
pathname.includes('.')
) {
return NextResponse.next();
}
// Check if the request is for a protected API route
if (pathname.startsWith('/api/')) {
// Skip CSRF endpoint - it handles its own auth
if (pathname === '/api/csrf') {
return NextResponse.next();
}
// Get the session token
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
// If no token, user is not authenticated
if (!token) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
);
}
// For state-changing operations, we'll let the route handlers validate CSRF
// This middleware just ensures authentication
return NextResponse.next();
}
// For protected pages, redirect to signin if not authenticated
if (pathname.startsWith('/mockingjar')) {
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
if (!token && !pathname.startsWith('/mockingjar/auth')) {
const signInUrl = new URL('/mockingjar/auth/signin', request.url);
signInUrl.searchParams.set('callbackUrl', request.url);
return NextResponse.redirect(signInUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder files
*/
'/((?!_next/static|_next/image|favicon.ico|public).*)',
],
};