-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathmiddleware.ts
More file actions
49 lines (38 loc) · 1.32 KB
/
middleware.ts
File metadata and controls
49 lines (38 loc) · 1.32 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
42
43
44
45
46
47
48
49
import {NextRequest, NextResponse} from 'next/server';
const DOCS_PREFIX = '/docs';
const RAW_PREFIX = '/docs/raw';
const DEFAULT_SLUG = 'introduction';
function acceptsMarkdown(request: NextRequest) {
const accept = request.headers.get('accept');
return accept ? accept.toLowerCase().includes('text/markdown') : false;
}
function getDocsSlug(pathname: string) {
const slug = pathname.replace(/^\/docs\/?/, '');
return slug.length > 0 ? slug : DEFAULT_SLUG;
}
function endsWithMd(pathname: string) {
return pathname.endsWith('.md');
}
export function middleware(request: NextRequest) {
const {pathname} = request.nextUrl;
if (!pathname.startsWith(DOCS_PREFIX) || pathname.startsWith(RAW_PREFIX)) {
return NextResponse.next();
}
const wantsMd = endsWithMd(pathname);
const wantsMarkdown = wantsMd || acceptsMarkdown(request);
if (!wantsMarkdown) {
const response = NextResponse.next();
response.headers.set('Vary', 'Accept');
return response;
}
const rawPathname = wantsMd ? pathname.slice(0, -3) : pathname;
const slug = getDocsSlug(rawPathname);
const url = request.nextUrl.clone();
url.pathname = `${RAW_PREFIX}/${slug}`;
const response = NextResponse.rewrite(url);
response.headers.set('Vary', 'Accept');
return response;
}
export const config = {
matcher: ['/docs/:path*'],
};