MCPcopy
hub / github.com/GitbookIO/gitbook / middleware

Function middleware

packages/gitbook/src/middleware.ts:39–66  ·  view source on GitHub ↗
(request: NextRequest)

Source from the content-addressed store, hash-verified

37type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
38
39export async function middleware(request: NextRequest) {
40 try {
41 const requestURL = new URL(request.url);
42
43 // Redirect to normalize the URL
44 const normalized = normalizeURL(requestURL);
45 if (normalized.toString() !== requestURL.toString()) {
46 return NextResponse.redirect(normalized.toString());
47 }
48
49 // Reject malicious requests
50 const rejectResponse = await validateServerActionRequest(request);
51 if (rejectResponse) {
52 return rejectResponse;
53 }
54
55 for (const handler of [serveSiteRoutes, serveSpacePDFRoutes]) {
56 const result = await handler(requestURL, request);
57 if (result) {
58 return result;
59 }
60 }
61
62 return NextResponse.next();
63 } catch (error) {
64 return serveErrorResponse(error as Error);
65 }
66}
67
68async function validateServerActionRequest(request: NextRequest) {
69 // First thing we need to do is validate that the header is in a correct format.

Callers

nothing calls this directly

Calls 5

normalizeURLFunction · 0.90
serveErrorResponseFunction · 0.85
toStringMethod · 0.80
handlerFunction · 0.50

Tested by

no test coverage detected