import { clerkMiddleware } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; export default clerkMiddleware(async (auth, req) => { const { pathname } = req.nextUrl; // 定义公开路由 const publicRoutes = [ "/", "/favicon.ico", "/api/courses", ]; // 检查是否是公开路由 const isPublicRoute = publicRoutes.some(route => pathname === route) || pathname.match(/^\/api\/courses\/[^\/]+\/classrooms$/) || pathname.match(/^\/api\/classrooms\/[^\/]+\/assignments$/) || pathname.match(/^\/api\/assignments\/[^\/]+\/submissions$/) || pathname.match(/^\/api\/assignments\/[^\/]+\/submissions\/upload$/); // 如果不是公开路由,则需要认证 if (!isPublicRoute) { const { userId } = await auth(); if (!userId && pathname.startsWith("/api/")) { return NextResponse.json({ error: "未授权" }, { status: 401 }); } if (!userId) { return NextResponse.redirect(new URL("/", req.url)); } } return NextResponse.next(); }); export const config = { matcher: [ "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)", ], };