-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
39 lines (31 loc) · 1.3 KB
/
middleware.ts
File metadata and controls
39 lines (31 loc) · 1.3 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
import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
const MARKDOWN_TYPES = ['text/markdown', 'text/x-markdown', 'text/plain'];
function isMarkdownPreferred(request: NextRequest): boolean {
const accept = request.headers.get('accept') ?? '';
return MARKDOWN_TYPES.some((type) => accept.includes(type));
}
function isProgrammaticClient(request: NextRequest): boolean {
// Browsers always send Sec-Fetch-Dest; curl/WebFetch/python-requests do not
return !request.headers.has('sec-fetch-dest');
}
export default function middleware(request: NextRequest, event: NextFetchEvent) {
const { pathname } = request.nextUrl;
if (pathname === '/' && isProgrammaticClient(request)) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = '/llms.txt';
return NextResponse.redirect(redirectUrl);
}
if (isMarkdownPreferred(request) && !pathname.startsWith('/llms')) {
const rewriteUrl = request.nextUrl.clone();
rewriteUrl.pathname = `/llms.mdx${pathname}`;
return NextResponse.rewrite(rewriteUrl);
}
return NextResponse.next();
}
export const config = {
matcher: [
// Match all paths except Next.js internals, API routes, and static files
'/((?!_next|api/).*)', // This excludes /api/ but includes /apis/
],
};