rowboat/apps/rowboat/middleware.ts

71 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-01-13 15:31:31 +05:30
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
2025-06-24 12:07:30 +05:30
import { auth0 } from "./app/lib/auth0";
2025-01-13 15:31:31 +05:30
const corsOptions = {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, x-client-id, Authorization',
}
2025-07-24 20:11:21 +05:30
async function authCheck(request: NextRequest) {
const session = await auth0.getSession(request);
const loginUrl = new URL('/auth/login', request.url);
loginUrl.searchParams.set('returnTo', request.nextUrl.pathname + request.nextUrl.search);
if (!session) {
return NextResponse.redirect(loginUrl);
}
return auth0.middleware(request);
}
2025-01-13 15:31:31 +05:30
export async function middleware(request: NextRequest, event: NextFetchEvent) {
2025-06-24 12:07:30 +05:30
// Check if the request path starts with /api/auth/
if (request.nextUrl.pathname.startsWith('/auth')) {
return await auth0.middleware(request);
2025-06-24 12:07:30 +05:30
}
2025-01-13 15:31:31 +05:30
// Check if the request path starts with /api/
if (request.nextUrl.pathname.startsWith('/api/')) {
// Handle preflighted requests
if (request.method === 'OPTIONS') {
const preflightHeaders = {
'Access-Control-Allow-Origin': '*',
...corsOptions,
}
return NextResponse.json({}, { headers: preflightHeaders });
}
// Handle simple requests
const response = NextResponse.next();
2025-05-18 01:37:54 +05:30
2025-01-13 15:31:31 +05:30
// Set CORS headers for all origins
response.headers.set('Access-Control-Allow-Origin', '*');
2025-05-18 01:37:54 +05:30
2025-01-13 15:31:31 +05:30
Object.entries(corsOptions).forEach(([key, value]) => {
response.headers.set(key, value);
})
return response;
}
2025-05-18 01:37:54 +05:30
if (request.nextUrl.pathname.startsWith('/projects') ||
request.nextUrl.pathname.startsWith('/billing') ||
request.nextUrl.pathname.startsWith('/onboarding')) {
2025-03-27 07:58:15 +05:30
// Skip auth check if USE_AUTH is not enabled
2025-06-24 12:07:30 +05:30
if (process.env.USE_AUTH === 'true') {
2025-07-24 20:11:21 +05:30
return await authCheck(request);
2025-03-27 07:58:15 +05:30
}
2025-01-13 15:31:31 +05:30
}
return NextResponse.next();
}
export const config = {
2025-05-18 01:37:54 +05:30
matcher: [
2025-06-24 12:07:30 +05:30
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
2025-05-18 01:37:54 +05:30
],
2025-06-24 12:07:30 +05:30
};