Spaces:
Sleeping
Sleeping
| import { NextResponse, type NextRequest } from 'next/server'; | |
| import { getToken } from 'next-auth/jwt'; | |
| import { guestRegex, isDevelopmentEnvironment } from './lib/constants'; | |
| export async function middleware(request: NextRequest) { | |
| const { pathname } = request.nextUrl; | |
| /* | |
| * Playwright starts the dev server and requires a 200 status to | |
| * begin the tests, so this ensures that the tests can start | |
| */ | |
| if (pathname.startsWith('/ping')) { | |
| return new Response('pong', { status: 200 }); | |
| } | |
| if (pathname.startsWith('/api/auth')) { | |
| return NextResponse.next(); | |
| } | |
| // For Hugging Face Spaces, skip middleware auth checks | |
| // The auth() function will handle auto-guest creation | |
| if (process.env.HF_SPACE === 'true') { | |
| return NextResponse.next(); | |
| } | |
| const token = await getToken({ | |
| req: request, | |
| secret: process.env.AUTH_SECRET, | |
| secureCookie: !isDevelopmentEnvironment, | |
| }); | |
| if (!token) { | |
| // Regular non-iframe flow | |
| const redirectUrl = encodeURIComponent(request.url); | |
| const retryCount = request.cookies.get('auth-retry')?.value || '0'; | |
| if (parseInt(retryCount) > 2) { | |
| const response = NextResponse.next(); | |
| response.cookies.delete('auth-retry'); | |
| return response; | |
| } | |
| const response = NextResponse.redirect( | |
| new URL(`/api/auth/guest?redirectUrl=${redirectUrl}`, request.url), | |
| ); | |
| response.cookies.set('auth-retry', String(parseInt(retryCount) + 1)); | |
| return response; | |
| } | |
| const isGuest = guestRegex.test(token?.email ?? ''); | |
| if (token && !isGuest && ['/login', '/register'].includes(pathname)) { | |
| return NextResponse.redirect(new URL('/', request.url)); | |
| } | |
| return NextResponse.next(); | |
| } | |
| export const config = { | |
| matcher: [ | |
| '/', | |
| '/chat/:id', | |
| '/api/:path*', | |
| '/login', | |
| '/register', | |
| /* | |
| * 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).*)', | |
| ], | |
| }; | |