All files / Bandstand/src middleware.ts

100% Statements 25/25
100% Branches 8/8
100% Functions 1/1
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 391x     1x 1x 1x 1x     1x 1x 1x   1x 1x   1x 8x   8x     7x 7x 7x 5x 5x       1x 1x 1x 1x   1x 1x 1x  
import {NextResponse, type NextRequest} from 'next/server'
 
// Session cookie names NextAuth uses (secure prefix when served over https)
const SESSION_COOKIES = [
  '__Secure-next-auth.session-token',
  'next-auth.session-token',
]
 
// Read-only endpoints that are deliberately public
const PUBLIC_API = [
  /^\/api\/auth\//,
  /^\/api\/health$/,
  // Calendar apps fetch the feed with no session; its URL holds a secret
  /^\/api\/calendar\/[^/]+$/,
]
 
export function middleware(req: NextRequest) {
  const {pathname, search} = req.nextUrl
 
  if (pathname.startsWith('/api/')) {
    // The route guards throw a Response, which Next.js turns into a 500.
    // Answer the common case (no session at all) here with a proper 401.
    const signedIn = SESSION_COOKIES.some((c) => req.cookies.has(c))
    if (!signedIn && !PUBLIC_API.some((r) => r.test(pathname)))
      return new NextResponse('Unauthorized', {status: 401})
    return NextResponse.next()
  }
 
  // Expose the requested path to server layouts so a sign-in redirect can
  // return the user to the page they asked for.
  const headers = new Headers(req.headers)
  headers.set('x-pathname', pathname + search)
  return NextResponse.next({request: {headers}})
}
 
export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}