-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathwith-routes.ts
More file actions
468 lines (385 loc) · 13.5 KB
/
Copy pathwith-routes.ts
File metadata and controls
468 lines (385 loc) · 13.5 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auth } from '~/auth';
import { client } from '~/client';
import { graphql } from '~/client/graphql';
import { revalidate } from '~/client/revalidate-target';
import { prefixes } from '~/i18n/locales';
import { getVisitIdCookie, getVisitorIdCookie } from '~/lib/analytics/bigcommerce';
import { sendProductViewedEvent } from '~/lib/analytics/bigcommerce/data-events';
import { kvKey, STORE_STATUS_KEY } from '~/lib/kv/keys';
import { kv } from '../lib/kv';
import { type ProxyFactory } from './compose-proxies';
const trailingSlashDisabled = process.env.TRAILING_SLASH === 'false';
const GetRouteQuery = graphql(`
query GetRouteQuery($path: String!) {
site {
route(path: $path, redirectBehavior: FOLLOW) {
redirect {
to {
__typename
... on BlogPostRedirect {
path
}
... on BrandRedirect {
path
}
... on CategoryRedirect {
path
}
... on PageRedirect {
path
}
... on ProductRedirect {
path
}
... on ManualRedirect {
url
}
}
fromPath
toUrl
}
node {
__typename
id
... on Product {
entityId
}
... on Category {
entityId
}
... on Brand {
entityId
}
... on BlogPost {
entityId
}
}
}
}
}
`);
const getRoute = async (path: string, channelId?: string, customerAccessToken?: string) => {
const response = await client.fetch({
document: GetRouteQuery,
variables: { path },
customerAccessToken,
fetchOptions: { next: { revalidate } },
channelId,
});
return response.data.site.route;
};
const getRawWebPageContentQuery = graphql(`
query getRawWebPageContent($id: ID!) {
node(id: $id) {
__typename
... on RawHtmlPage {
htmlBody
}
}
}
`);
const getRawWebPageContent = async (id: string, customerAccessToken?: string) => {
const response = await client.fetch({
document: getRawWebPageContentQuery,
variables: { id },
fetchOptions: { next: { revalidate } },
customerAccessToken,
});
const node = response.data.node;
if (node?.__typename !== 'RawHtmlPage') {
throw new Error('Failed to fetch raw web page content');
}
return node;
};
const GetStoreStatusQuery = graphql(`
query getStoreStatus {
site {
settings {
status
}
}
}
`);
const getStoreStatus = async (channelId?: string) => {
const { data } = await client.fetch({
document: GetStoreStatusQuery,
fetchOptions: { next: { revalidate: 300 } },
channelId,
});
return data.site.settings?.status;
};
type Route = Awaited<ReturnType<typeof getRoute>>;
type StorefrontStatusType = ReturnType<typeof graphql.scalar<'StorefrontStatusType'>>;
interface RouteCache {
route: Route;
expiryTime: number;
}
interface StorefrontStatusCache {
status: StorefrontStatusType;
expiryTime: number;
}
const StorefrontStatusCacheSchema = z.object({
status: z.union([
z.literal('HIBERNATION'),
z.literal('LAUNCHED'),
z.literal('MAINTENANCE'),
z.literal('PRE_LAUNCH'),
]),
expiryTime: z.number(),
});
const RedirectSchema = z.object({
to: z.union([
z.object({ __typename: z.literal('BlogPostRedirect'), path: z.string() }),
z.object({ __typename: z.literal('BrandRedirect'), path: z.string() }),
z.object({ __typename: z.literal('CategoryRedirect'), path: z.string() }),
z.object({ __typename: z.literal('PageRedirect'), path: z.string() }),
z.object({ __typename: z.literal('ProductRedirect'), path: z.string() }),
z.object({ __typename: z.literal('ManualRedirect'), url: z.string() }),
]),
fromPath: z.string(),
toUrl: z.string(),
});
const NodeSchema = z.union([
z.object({ __typename: z.literal('Product'), entityId: z.number() }),
z.object({ __typename: z.literal('Category'), entityId: z.number() }),
z.object({ __typename: z.literal('Brand'), entityId: z.number() }),
z.object({ __typename: z.literal('ContactPage'), id: z.string() }),
z.object({ __typename: z.literal('NormalPage'), id: z.string() }),
z.object({ __typename: z.literal('RawHtmlPage'), id: z.string() }),
z.object({ __typename: z.literal('Blog'), id: z.string() }),
z.object({ __typename: z.literal('BlogPost'), entityId: z.number() }),
]);
const RouteSchema = z.object({
redirect: z.nullable(RedirectSchema),
node: z.nullable(NodeSchema),
});
const RouteCacheSchema = z.object({
route: z.nullable(RouteSchema),
expiryTime: z.number(),
});
const updateRouteCache = async (
pathname: string,
channelId: string,
event: NextFetchEvent,
): Promise<RouteCache> => {
const routeCache: RouteCache = {
route: await getRoute(pathname, channelId),
expiryTime: Date.now() + 1000 * 60 * 30, // 30 minutes
};
event.waitUntil(kv.set(kvKey(pathname, channelId), routeCache));
return routeCache;
};
const updateStatusCache = async (
channelId: string,
event: NextFetchEvent,
): Promise<StorefrontStatusCache> => {
const status = await getStoreStatus(channelId);
if (status === undefined) {
throw new Error('Failed to fetch new storefront status');
}
const statusCache: StorefrontStatusCache = {
status,
expiryTime: Date.now() + 1000 * 60 * 5, // 5 minutes
};
event.waitUntil(kv.set(kvKey(STORE_STATUS_KEY, channelId), statusCache));
return statusCache;
};
const clearLocaleFromPath = (path: string, locale: string) => {
const prefix = prefixes[locale] ?? `/${locale}`;
if (path === prefix || path === `${prefix}/`) {
return '/';
}
if (path.startsWith(`${prefix}/`)) {
return path.replace(prefix, '');
}
return path;
};
function normalizeForCompare(url: URL): string {
if (trailingSlashDisabled && url.pathname !== '/' && url.pathname.endsWith('/')) {
return `${url.pathname.replace(/\/+$/, '')}${url.search}`;
}
if (!trailingSlashDisabled && !url.pathname.endsWith('/')) {
return `${url.pathname}/${url.search}`;
}
return `${url.pathname}${url.search}`;
}
const sameInternalUrl = (a: URL, b: URL) =>
a.origin === b.origin && normalizeForCompare(a) === normalizeForCompare(b);
const getRouteInfo = async (
request: NextRequest,
event: NextFetchEvent,
customerAccessToken?: string,
) => {
const locale = request.headers.get('x-bc-locale') ?? '';
const channelId = request.headers.get('x-bc-channel-id') ?? '';
try {
// For route resolution parity, we need to also include query params, otherwise certain redirects will not work.
const pathname = clearLocaleFromPath(request.nextUrl.pathname + request.nextUrl.search, locale);
let [routeCache, statusCache] = await kv.mget<RouteCache | StorefrontStatusCache>(
kvKey(pathname, channelId),
kvKey(STORE_STATUS_KEY, channelId),
);
// If caches are old, update them in the background and return the old data (SWR-like behavior)
// If cache is missing, update it and return the new data, but write to KV in the background
if (statusCache && statusCache.expiryTime < Date.now()) {
event.waitUntil(updateStatusCache(channelId, event));
} else if (!statusCache) {
statusCache = await updateStatusCache(channelId, event);
}
const parsedStatus = StorefrontStatusCacheSchema.safeParse(statusCache);
const status = parsedStatus.success ? parsedStatus.data.status : undefined;
// The KV route cache is shared across customers and isn't namespaced by
// identity. Authenticated requests bypass it entirely so customer-specific
// route resolutions can't leak across users in either direction.
if (customerAccessToken) {
return {
route: await getRoute(pathname, channelId, customerAccessToken),
status,
};
}
if (routeCache && routeCache.expiryTime < Date.now()) {
event.waitUntil(updateRouteCache(pathname, channelId, event));
} else if (!routeCache) {
routeCache = await updateRouteCache(pathname, channelId, event);
}
const parsedRoute = RouteCacheSchema.safeParse(routeCache);
return {
route: parsedRoute.success ? parsedRoute.data.route : undefined,
status,
};
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
return {
route: undefined,
status: undefined,
};
}
};
export const withRoutes: ProxyFactory = () => {
return (request, event) =>
// eslint-disable-next-line complexity
auth(async (req) => {
const locale = req.headers.get('x-bc-locale') ?? '';
const customerAccessToken = req.auth?.user?.customerAccessToken;
const { route, status } = await getRouteInfo(req, event, customerAccessToken);
if (status === 'MAINTENANCE') {
// 503 status code not working - https://github.com/vercel/next.js/issues/50155
return NextResponse.rewrite(new URL(`/${locale}/maintenance`, req.url), { status: 503 });
}
const redirectConfig = {
// Use 301 status code as it is more universally supported by crawlers
status: 301,
nextConfig: {
// Preserve the trailing slash if it was present in the original URL
// BigCommerce by default returns the trailing slash.
trailingSlash: process.env.TRAILING_SLASH !== 'false',
},
};
if (route?.redirect) {
// Only carry over query params if the fromPath does not have any, as Bigcommerce 301 redirects support matching by specific query params.
const fromPathSearchParams = new URL(route.redirect.fromPath, req.url).search;
const searchParams = fromPathSearchParams.length > 0 ? '' : req.nextUrl.search;
switch (route.redirect.to.__typename) {
case 'BlogPostRedirect':
case 'BrandRedirect':
case 'CategoryRedirect':
case 'PageRedirect':
case 'ProductRedirect': {
// For dynamic redirects, assume an internal redirect and construct the URL from the path
const redirectUrl = new URL(route.redirect.to.path + searchParams, req.url);
if (sameInternalUrl(req.nextUrl, redirectUrl)) {
break;
}
return NextResponse.redirect(redirectUrl, redirectConfig);
}
case 'ManualRedirect': {
// For manual redirects, to.url will be a relative path if it is an internal redirect and an absolute URL if it is an external redirect.
// URL constructor will correctly handle both cases.
// If the manual redirect is an external URL, we should not carry query params.
const redirectUrl = new URL(route.redirect.to.url, req.url);
if (redirectUrl.origin === req.nextUrl.origin) {
redirectUrl.search = searchParams;
if (sameInternalUrl(req.nextUrl, redirectUrl)) {
break;
}
}
return NextResponse.redirect(redirectUrl, redirectConfig);
}
default: {
// If for some reason the redirect type is not recognized, use the toUrl as a fallback
return NextResponse.redirect(route.redirect.toUrl, redirectConfig);
}
}
}
const node = route?.node;
let url: string;
switch (node?.__typename) {
case 'Brand': {
url = `/${locale}/brand/${node.entityId}`;
break;
}
case 'Category': {
url = `/${locale}/category/${node.entityId}`;
break;
}
case 'Product': {
url = `/${locale}/product/${node.entityId}`;
const isPrefetch = req.headers.get('Next-Router-Prefetch') === '1';
const isRSC = req.headers.get('RSC') === '1';
if (!isPrefetch && !isRSC) {
event.waitUntil(recordProductVisit(req, node.entityId));
}
break;
}
case 'NormalPage': {
url = `/${locale}/webpages/${node.id}/normal/`;
break;
}
case 'ContactPage': {
url = `/${locale}/webpages/${node.id}/contact/`;
break;
}
case 'RawHtmlPage': {
const { htmlBody } = await getRawWebPageContent(node.id, customerAccessToken);
return new NextResponse(htmlBody, {
headers: { 'content-type': 'text/html' },
});
}
case 'Blog': {
url = `/${locale}/blog`;
break;
}
case 'BlogPost': {
url = `/${locale}/blog/${node.entityId}`;
break;
}
default: {
const { pathname } = new URL(req.url);
const cleanPathName = clearLocaleFromPath(pathname, locale);
url = `/${locale}${cleanPathName}`;
}
}
const rewriteUrl = new URL(url, req.url);
rewriteUrl.search = req.nextUrl.search;
return NextResponse.rewrite(rewriteUrl);
// @ts-expect-error auth() overload expects middleware return type, but we return NextResponse directly for the proxy
})(request, event);
};
async function recordProductVisit(request: Request, productId: number) {
const visitId = await getVisitIdCookie();
const visitorId = await getVisitorIdCookie();
if (visitId && visitorId) {
await sendProductViewedEvent({
productId,
initiator: { visitId, visitorId },
request: {
url: request.url,
refererUrl: request.headers.get('referer') || '',
userAgent: request.headers.get('user-agent') || '',
},
});
}
}