Skip to content

Commit c0b03d7

Browse files
committed
Try with a custom entrypoint
1 parent 2835484 commit c0b03d7

File tree

7 files changed

+86
-23
lines changed

7 files changed

+86
-23
lines changed

bun.lockb

80 Bytes
Binary file not shown.

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
},
99
"packageManager": "[email protected]",
1010
"patchedDependencies": {
11-
"@vercel/[email protected]": "patches/@vercel%[email protected]"
11+
"@vercel/[email protected]": "patches/@vercel%[email protected]",
12+
"@cloudflare/[email protected]": "patches/@cloudflare%[email protected]"
1213
},
1314
"private": true,
1415
"scripts": {

packages/gitbook/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"scripts": {
66
"dev": "env-cmd --silent -f ../../.env.local next dev",
77
"build": "next build",
8-
"build:cloudflare": "next-on-pages",
8+
"build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts",
99
"start": "next start",
1010
"lint": "next lint",
1111
"typecheck": "tsc --noEmit",
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// @ts-ignore
2+
import nextOnPagesHandler from '@cloudflare/next-on-pages/fetch-handler';
3+
4+
import { withMiddlewareHeadersStorage } from './lib/middleware';
5+
6+
/**
7+
* We use a custom entrypoint until we can move to opennext (https://github.com/opennextjs/opennextjs-cloudflare/issues/92).
8+
* There is a bug in next-on-pages where headers can't be set on the response in the middleware for RSC requests (https://github.com/cloudflare/next-on-pages/issues/897).
9+
*/
10+
export default {
11+
async fetch(request, env, ctx) {
12+
console.log('start custom fetch');
13+
const response = await withMiddlewareHeadersStorage(() =>
14+
nextOnPagesHandler.fetch(request, env, ctx),
15+
);
16+
console.log('end custom fetch');
17+
18+
return response;
19+
},
20+
} as ExportedHandler<{ ASSETS: Fetcher }>;

packages/gitbook/src/lib/middleware.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,37 @@
1+
import { AsyncLocalStorage } from 'node:async_hooks';
2+
3+
const responseHeadersLocalStorage = new AsyncLocalStorage<Headers>();
4+
5+
/**
6+
* Set a header on the middleware response.
7+
* We do this because of https://github.com/opennextjs/opennextjs-cloudflare/issues/92
8+
* It can be removed as soon as we move to opennext where hopefully this is fixed.
9+
*/
10+
export function setMiddlewareHeader(response: Response, name: string, value: string) {
11+
const responseHeaders = responseHeadersLocalStorage.getStore();
12+
response.headers.set(name, value);
13+
14+
if (responseHeaders) {
15+
responseHeaders.set(name, value);
16+
}
17+
}
18+
19+
/**
20+
* Wrap some middleware with a the storage to store headers.
21+
*/
22+
export async function withMiddlewareHeadersStorage(
23+
handler: () => Promise<Response>,
24+
): Promise<Response> {
25+
const responseHeaders = new Headers();
26+
const response = await responseHeadersLocalStorage.run(responseHeaders, handler);
27+
28+
for (const [name, value] of responseHeaders.entries()) {
29+
response.headers.set(name, value);
30+
}
31+
32+
return response;
33+
}
34+
135
/**
236
* For a given GitBook URL, return a list of alternative URLs that could be matched against to lookup the content.
337
* The approach is optimized to aim at reusing cached lookup results as much as possible.

packages/gitbook/src/middleware.ts

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
import { race } from '@/lib/async';
2121
import { buildVersion } from '@/lib/build';
2222
import { createContentSecurityPolicyNonce, getContentSecurityPolicy } from '@/lib/csp';
23-
import { getURLLookupAlternatives, normalizeURL } from '@/lib/middleware';
23+
import { getURLLookupAlternatives, normalizeURL, setMiddlewareHeader } from '@/lib/middleware';
2424
import {
2525
VisitorAuthCookieValue,
2626
getVisitorAuthCookieName,
@@ -253,14 +253,14 @@ export async function middleware(request: NextRequest) {
253253
resolved.cookies,
254254
);
255255

256-
response.headers.set('x-gitbook-version', buildVersion());
256+
setMiddlewareHeader(response, 'x-gitbook-version', buildVersion());
257257

258258
// Add Content Security Policy header
259-
response.headers.set('content-security-policy', csp);
259+
setMiddlewareHeader(response, 'content-security-policy', csp);
260260
// Basic security headers
261-
response.headers.set('strict-transport-security', 'max-age=31536000');
262-
response.headers.set('referrer-policy', 'no-referrer-when-downgrade');
263-
response.headers.set('x-content-type-options', 'nosniff');
261+
setMiddlewareHeader(response, 'strict-transport-security', 'max-age=31536000');
262+
setMiddlewareHeader(response, 'referrer-policy', 'no-referrer-when-downgrade');
263+
setMiddlewareHeader(response, 'x-content-type-options', 'nosniff');
264264

265265
const isPrefetch = request.headers.has('x-middleware-prefetch');
266266

@@ -273,28 +273,24 @@ export async function middleware(request: NextRequest) {
273273
// 'private, no-cache, no-store, max-age=0, must-revalidate',
274274
// );
275275
// } else {
276-
if (typeof resolved.cacheMaxAge === 'number') {
277-
const cacheControl = `public, max-age=0, s-maxage=${resolved.cacheMaxAge}, stale-if-error=0`;
278-
279-
if (
280-
process.env.GITBOOK_OUTPUT_CACHE === 'true' &&
281-
process.env.NODE_ENV !== 'development'
282-
) {
283-
response.headers.set('cache-control', cacheControl);
284-
response.headers.set('Cloudflare-CDN-Cache-Control', cacheControl);
285-
} else {
286-
response.headers.set('x-gitbook-cache-control', cacheControl);
287-
}
276+
if (typeof resolved.cacheMaxAge === 'number') {
277+
const cacheControl = `public, max-age=0, s-maxage=${resolved.cacheMaxAge}, stale-if-error=0`;
278+
279+
if (process.env.GITBOOK_OUTPUT_CACHE === 'true' && process.env.NODE_ENV !== 'development') {
280+
setMiddlewareHeader(response, 'cache-control', cacheControl);
281+
setMiddlewareHeader(response, 'Cloudflare-CDN-Cache-Control', cacheControl);
282+
} else {
283+
setMiddlewareHeader(response, 'x-gitbook-cache-control', cacheControl);
288284
}
285+
}
289286
// }
290287

291288
if (resolved.cacheTags && resolved.cacheTags.length > 0) {
292289
const headerCacheTag = resolved.cacheTags.join(',');
293-
response.headers.set('cache-tag', headerCacheTag);
294-
response.headers.set('x-gitbook-cache-tag', headerCacheTag);
290+
setMiddlewareHeader(response, 'cache-tag', headerCacheTag);
291+
setMiddlewareHeader(response, 'x-gitbook-cache-tag', headerCacheTag);
295292
}
296293

297-
console.log('headers end', Array.from(response.headers.entries()));
298294
return response;
299295
}
300296

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
diff --git a/dist/index.js b/dist/index.js
2+
index 32fec63484ec332eb291a7253e5e168223627535..653dee64794140bafe57219356c712b197c17530 100644
3+
--- a/dist/index.js
4+
+++ b/dist/index.js
5+
@@ -6983,6 +6983,7 @@ async function buildWorkerFile({ vercelConfig, vercelOutput }, {
6+
outfile: outputFile,
7+
allowOverwrite: true,
8+
bundle: true,
9+
+ external: ["node:*", "cloudflare:*"],
10+
plugins: [
11+
{
12+
name: "custom-entrypoint-import-plugin",

0 commit comments

Comments
 (0)