Skip to content

Commit 7bd6877

Browse files
authored
feat: add middleware to proxy requests to external generator (#911)
1 parent d229ac0 commit 7bd6877

2 files changed

Lines changed: 47 additions & 6 deletions

File tree

middleware.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Configuration for Vercel Edge Middleware (same as original)
2+
export const config = {
3+
// Matcher: all paths except those starting with /api
4+
matcher: ['/((?!api/).*)'],
5+
};
6+
7+
export default async function middleware(request: Request): Promise<Response | void> {
8+
const url = new URL(request.url);
9+
const { pathname, search } = url;
10+
11+
// Additional check to ensure /api paths don't pass through
12+
if (pathname.startsWith('/api')) {
13+
return; // let the request proceed to the serverless function
14+
}
15+
16+
// Build the target generator URL while preserving the path and query
17+
const generatorUrl = new URL(pathname + search, 'https://gh-readme-profile-generator.vercel.app');
18+
19+
// Prepare headers to forward
20+
const headers = new Headers();
21+
headers.set('User-Agent', request.headers.get('User-Agent') || '');
22+
headers.set('Accept', request.headers.get('Accept') || '*/*');
23+
// Do not forward the 'host' header to avoid interference
24+
25+
try {
26+
const response = await fetch(generatorUrl, {
27+
method: request.method,
28+
headers: headers,
29+
});
30+
31+
// Copy headers from the generator response, except for some unnecessary ones
32+
const responseHeaders = new Headers(response.headers);
33+
// Remove headers related to connection or original server if needed
34+
responseHeaders.delete('content-encoding');
35+
responseHeaders.delete('transfer-encoding');
36+
37+
return new Response(response.body, {
38+
status: response.status,
39+
statusText: response.statusText,
40+
headers: responseHeaders,
41+
});
42+
} catch (error) {
43+
// Handle errors by returning a 500 response or fallback
44+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
45+
return new Response('Proxy error: ' + errorMessage, { status: 500 });
46+
}
47+
}

vercel.json

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,6 @@
55
"maxDuration": 10
66
}
77
},
8-
"redirects": [
9-
{
10-
"source": "/",
11-
"destination": "https://gh-readme-profile-generator.vercel.app/"
12-
}
13-
],
148
"headers": [
159
{
1610
"source": "/api",

0 commit comments

Comments
 (0)