-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
34 lines (29 loc) · 1.16 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getLogtoContext } from '@logto/next/server-actions';
import { logtoConfig } from '@/app/logto';
import { PROTECTED_ROUTES, ALLOWED_ORIGINS } from '@/utils/constants';
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
// CORS handling
const origin = request.headers.get('origin');
if (origin && ALLOWED_ORIGINS.includes(origin)) {
response.headers.set('Access-Control-Allow-Origin', origin);
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
// Authentication check
const isProtectedRoute = PROTECTED_ROUTES.some((route) =>
request.nextUrl.pathname.startsWith(route)
);
if (isProtectedRoute) {
const { isAuthenticated } = await getLogtoContext(logtoConfig);
if (!isAuthenticated) {
return NextResponse.redirect(new URL('/auth-gate', request.url));
}
}
return response;
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};