Skip to content

Commit a3e0157

Browse files
committed
Allow passing (optional) custom headers function to proxy.to()
1 parent b1c71ba commit a3e0157

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

src/common/patch.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,8 @@ export function patchResponse(resp: Response, changes: ResponseInit): Response {
3535
});
3636
}
3737

38-
export interface HeaderChanges {
39-
[key: string]: string | null;
40-
}
38+
export type HeaderChanges = Record<string, string | null>;
39+
4140
// patchHeaders returns a copy of the headers with the applied changes
4241
export function patchHeaders(
4342
headers: Headers,

src/proxy/proxy.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ import { FetchEvent, ServeFunction } from '../types';
33

44
export type GetEndpoint = (req?: Request) => URL;
55

6+
type CustomHeaders = (req: Request) => HeaderChanges;
7+
68
export interface ProxyOptions {
79
host?: 'original' | 'xforwarded';
10+
headers?: CustomHeaders;
811
}
912

1013
const DEFAULT_OPTIONS: ProxyOptions = {
@@ -63,15 +66,22 @@ export function requestToUpstream(
6366
opts.host === 'original' ? original.hostname : upstream.hostname;
6467
url.protocol = upstream.protocol;
6568

66-
const customHeaders: HeaderChanges =
69+
const hostHeaders =
6770
opts.host === 'xforwarded'
6871
? {
69-
'X-Forwarded-Host': original.hostname,
70-
'X-Forwarded-Proto': original.protocol
71-
}
72+
'X-Forwarded-Host': original.hostname,
73+
'X-Forwarded-Proto': original.protocol
74+
}
7275
: {
73-
Host: original.hostname
74-
};
76+
Host: original.hostname
77+
};
78+
79+
const reqHeaders = opts.headers ? opts.headers(request) : {};
80+
81+
const customHeaders: HeaderChanges = {
82+
...(hostHeaders as any),
83+
...reqHeaders
84+
};
7585

7686
// Copy old headers
7787
const headers = patchHeaders(request.headers, customHeaders);

0 commit comments

Comments
 (0)