Skip to content

Commit 252afce

Browse files
conico974Nicolas Dorseuil
andauthored
Store customization in a cookie for preview route (#3707)
Co-authored-by: Nicolas Dorseuil <nicolas@gitbook.io>
1 parent bef1916 commit 252afce

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

packages/gitbook/src/lib/visitors.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export type ResponseCookie = {
1818
sameSite: boolean | 'lax' | 'strict' | 'none' | undefined;
1919
secure: boolean;
2020
maxAge: number;
21+
path: string;
2122
}>;
2223
};
2324

packages/gitbook/src/middleware.ts

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,16 +296,41 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
296296
requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(stableSiteURLData));
297297

298298
// Preview of customization/theme
299-
const customization = siteRequestURL.searchParams.get('customization');
299+
const customizationCookie = request.cookies.get(MiddlewareHeaders.Customization);
300+
const customization =
301+
siteRequestURL.searchParams.get('customization') ??
302+
(customizationCookie ? decodeURIComponent(customizationCookie.value) : undefined);
300303
if (customization && validateSerializedCustomization(customization)) {
301304
routeType = 'dynamic';
302305
// We need to encode the customization headers, otherwise it will fail for some customization values containing non ASCII chars on vercel.
303306
requestHeaders.set(MiddlewareHeaders.Customization, encodeURIComponent(customization));
307+
cookies.push({
308+
name: MiddlewareHeaders.Customization,
309+
value: encodeURIComponent(customization),
310+
options: {
311+
httpOnly: true,
312+
sameSite: 'lax',
313+
maxAge: 10 * 60, // 10 minutes
314+
path: '/url/preview', // Only send the cookie to preview routes
315+
},
316+
});
304317
}
305-
const theme = siteRequestURL.searchParams.get('theme');
318+
const theme =
319+
siteRequestURL.searchParams.get('theme') ??
320+
request.cookies.get(MiddlewareHeaders.Theme)?.value;
306321
if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) {
307322
routeType = 'dynamic';
308323
requestHeaders.set(MiddlewareHeaders.Theme, theme);
324+
cookies.push({
325+
name: MiddlewareHeaders.Theme,
326+
value: theme,
327+
options: {
328+
httpOnly: true,
329+
sameSite: 'lax',
330+
maxAge: 10 * 60, // 10 minutes
331+
path: '/url/preview', // Only send the cookie to preview routes
332+
},
333+
});
309334
}
310335

311336
// We support forcing dynamic routes by setting a `gitbook-dynamic-route` cookie

0 commit comments

Comments
 (0)