-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmiddleware.ts
More file actions
41 lines (34 loc) · 1.19 KB
/
middleware.ts
File metadata and controls
41 lines (34 loc) · 1.19 KB
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
39
40
41
import { NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) {
const acceptHeader = request.headers.get("accept") || "";
// Check if the request prefers markdown
if (acceptHeader.includes("text/markdown")) {
const pathname = request.nextUrl.pathname;
// Only handle top-level slug routes (not nested paths like /api/*, /rss/*, etc.)
// Match paths like /some-page but not /api/something or /rss/feed
const slugMatch = pathname.match(/^\/([^/]+)$/);
if (slugMatch) {
const slug = slugMatch[1];
// Exclude known non-doc routes
const excludedPaths = [
"favicon.ico",
"robots.txt",
"sitemap.xml",
];
if (!excludedPaths.includes(slug)) {
// Rewrite to the markdown API route
const url = request.nextUrl.clone();
url.pathname = `/api/markdown/${slug}`;
return NextResponse.rewrite(url);
}
}
}
return NextResponse.next();
}
export const config = {
// Only run middleware on paths that could be doc pages
// Exclude static files, api routes, and other known paths
matcher: [
"/((?!_next/static|_next/image|favicon.ico|api/|rss/).*)",
],
};