-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
157 lines (131 loc) · 5.27 KB
/
Copy pathproxy.ts
File metadata and controls
157 lines (131 loc) · 5.27 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { vanityCache } from './util/cacheService';
import { graphqlResults } from './services/gql';
interface VanityUrlEntry {
forwardTo: string ;
action: number;
identifier: string;
}
const VanityUrl404:VanityUrlEntry ={forwardTo:"404",action:404,identifier:"404"};
const cacheTTL = 600;
const vanityUrlPrefix="dotVanity:";
// Escape pathname for GraphQL query to prevent injection issues
function escapeGraphQLString(str: string): string {
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
async function checkVanityUrl (pathname: string): Promise<VanityUrlEntry> {
const pathKey = vanityUrlPrefix + pathname;
// Check cache first (including negative cache)
const cachedVanity:VanityUrlEntry = vanityCache.get(pathKey) as VanityUrlEntry;
if(cachedVanity !=null){
return cachedVanity;
}
// Escape pathname for GraphQL query
const escapedPathname = escapeGraphQLString(pathname);
// Use the same GraphQL query that your app uses for consistency
const query = `
{
page(url: "${escapedPathname}", site:"173aff42881a55a562cec436180999cf") {
vanityUrl {
action
forwardTo
uri
}
}
}
`;
const json = await graphqlResults(query);
const errors = json?.errors||[];
console.debug("errors.length:", errors.length);
console.debug("forwardTo:", json?.data?.page?.vanityUrl?.forwardTo);
if(errors && errors.length>0 || ! json?.data?.page?.vanityUrl?.forwardTo){
console.log("no vanity found for:", pathKey)
vanityCache.set(pathKey,VanityUrl404)
return VanityUrl404;
}
const foundVanityUrl = {forwardTo: json?.data?.page?.vanityUrl.forwardTo,action: json.data.page.vanityUrl.action,identifier: "vanityFound"};
console.debug("foundVanity", foundVanityUrl);
vanityCache.set(pathKey, foundVanityUrl, cacheTTL);
return foundVanityUrl;
}
export async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// Skip middleware for static files, API routes, and Next.js internals
if (
pathname.startsWith('/_next/') ||
pathname.startsWith('/api/') ||
pathname.startsWith('/static/') ||
pathname.startsWith('/favicon') ||
pathname.startsWith('/.well-known/') ||
// Skip files with extensions (CSS, JS, images, maps, etc.)
/\.[a-zA-Z0-9]+(\?|$)/.test(pathname) ||
// Skip common static file patterns
pathname.includes('.css') ||
pathname.includes('.js') ||
pathname.includes('.map') ||
pathname.includes('.ico') ||
pathname.includes('.png') ||
pathname.includes('.jpg') ||
pathname.includes('.svg')
) {
return NextResponse.next();
}
// Check for vanity URL
const vanityUrl:VanityUrlEntry = await checkVanityUrl(pathname);
if (vanityUrl && vanityUrl.action!=404) {
const { forwardTo, action } = vanityUrl;
// Ensure the redirect URL is properly formatted
let redirectUrl = forwardTo;
if (!redirectUrl.startsWith('http') && !redirectUrl.startsWith('/')) {
redirectUrl = '/' + redirectUrl;
}
// Use appropriate status code - handle all valid redirect codes
const validRedirectCodes = [301, 302, 303, 307, 308];
const statusCode = validRedirectCodes.includes(action) ? action : 302;
console.log(`Vanity URL redirect: ${pathname} → ${redirectUrl} (${statusCode})`);
return NextResponse.redirect(new URL(redirectUrl, request.url), statusCode);
}
// Flat /docs/{slug} → nested canonical from build-nav slug index.
// Use 302 while the nav redesign is in testing — 301s are sticky in browsers.
// Switch DOCS_SLUG_REDIRECT_STATUS to 301 for production cutover.
const DOCS_SLUG_REDIRECT_STATUS = 302;
try {
const {
getDocsSlugIndex,
lookupShallowDocsRedirect,
} = await import('@/services/docs/getDocsSlugIndex');
const index = await getDocsSlugIndex();
const canonical = lookupShallowDocsRedirect(pathname, index);
if (canonical) {
const target = new URL(canonical, request.url);
target.search = request.nextUrl.search;
console.log(
`Docs slug redirect: ${pathname} → ${canonical} (${DOCS_SLUG_REDIRECT_STATUS})`,
);
return NextResponse.redirect(target, DOCS_SLUG_REDIRECT_STATUS);
}
} catch (error) {
console.error('Docs slug index redirect failed:', error);
}
let response = NextResponse.next();
response.headers.set("Cache-Control", "public, s-maxage=600, stale-while-revalidate=120");
response.headers.set("CDN-Cache-Control", "public, s-maxage=600, stale-while-revalidate=120");
response.headers.set("Vercel-CDN-Cache-Control", "public, s-maxage=600, stale-while-revalidate=1200");
response.headers.set("X-dotcms", "oh yes!");
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - Files with extensions (.css, .js, .png, etc.)
* - Well-known paths (.well-known/)
*/
'/((?!api|_next/static|_next/image|favicon.ico|.*\\.[a-zA-Z0-9]+$|\\.well-known).*)',
],
}