Skip to content

Commit 8a9d240

Browse files
fix(router): keep RESPONSE headers when dispatching a fetch-only event (#2777)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 033f6e8 commit 8a9d240

2 files changed

Lines changed: 67 additions & 5 deletions

File tree

‎packages/router/server/src/server-fn/dispatch.spec.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { DestroyRef, Injectable, Injector, inject } from '@angular/core';
2-
import { BASE_URL, LOCALE, REQUEST } from '@analogjs/router/tokens';
2+
import { BASE_URL, LOCALE, REQUEST, RESPONSE } from '@analogjs/router/tokens';
33
import { beforeEach, describe, expect, it, vi } from 'vitest';
44

55
import { dispatchServerFn } from './dispatch';
@@ -133,6 +133,38 @@ describe('dispatchServerFn', () => {
133133
expect(result).toEqual({ status: 200, body: 'example.com' });
134134
});
135135

136+
it('returns headers set through RESPONSE on a fetch-only event', async () => {
137+
serverFn({ id: 'cookies' }, async () => {
138+
const res = inject(RESPONSE);
139+
res.setHeader('set-cookie', ['a=1']);
140+
res.setHeader('x-app', 'app');
141+
res.setHeader('x-both', 'app');
142+
return new Response(null, {
143+
status: 303,
144+
headers: [
145+
['location', '/next'],
146+
['x-both', 'response'],
147+
['set-cookie', 'b=2'],
148+
['set-cookie', 'c=3'],
149+
],
150+
});
151+
});
152+
153+
const result = await dispatchServerFn(
154+
'cookies',
155+
undefined,
156+
{ req: new Request('http://example.com/_analog/fn/cookies') } as never,
157+
{ method: 'GET' },
158+
);
159+
160+
expect(result.headers).toEqual({
161+
'set-cookie': ['a=1', 'b=2', 'c=3'],
162+
'x-app': 'app',
163+
'x-both': 'response',
164+
location: '/next',
165+
});
166+
});
167+
136168
it('404s an unknown function', async () => {
137169
const result = await dispatchServerFn('nope', undefined, eventFor(), {
138170
method: 'GET',

‎packages/router/server/src/server-fn/dispatch.ts‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ import {
55
} from '@angular/core';
66
import { BASE_URL, LOCALE, REQUEST, RESPONSE } from '@analogjs/router/tokens';
77
import type { H3Event } from 'h3';
8+
import type { ServerResponse } from 'node:http';
89

910
import { detectLocale, getBaseUrl } from '../provide-server-context';
11+
import type { AnalogRequestContext } from '../request-handler';
1012
import { serverFnRegistry } from './registry';
1113
import { assertNodeContext, nodeContext } from './node-context';
1214
import { SERVER_FN_INTERCEPTORS, runInterceptors } from './interceptors';
@@ -76,12 +78,22 @@ export async function dispatchServerFn(
7678
rawInput: unknown,
7779
event: Pick<H3Event, 'node'> & { req?: unknown },
7880
options: DispatchServerFnOptions = {},
81+
): Promise<DispatchResult> {
82+
if (event.node?.req || !(event.req instanceof Request)) {
83+
return dispatchInContext(id, rawInput, assertNodeContext(event), options);
84+
}
85+
const context = nodeContext(event.req, new URL(event.req.url));
86+
const result = await dispatchInContext(id, rawInput, context, options);
87+
return withContextHeaders(result, context.res);
88+
}
89+
90+
async function dispatchInContext(
91+
id: string,
92+
rawInput: unknown,
93+
node: AnalogRequestContext,
94+
options: DispatchServerFnOptions,
7995
): Promise<DispatchResult> {
8096
const { parent, providers = [], method, allowedOrigins = [] } = options;
81-
const node =
82-
event.node?.req || !(event.req instanceof Request)
83-
? assertNodeContext(event)
84-
: nodeContext(event.req, new URL(event.req.url));
8597
const headers = (node.req.headers ?? {}) as HeaderBag;
8698

8799
// Same-origin guard runs first — before we even confirm the function exists —
@@ -189,6 +201,24 @@ export async function dispatchServerFn(
189201
return { status: 200, body: outcome };
190202
}
191203

204+
/** Headers set through `RESPONSE`, under those of a returned `Response`. */
205+
function withContextHeaders(
206+
result: DispatchResult,
207+
res: ServerResponse,
208+
): DispatchResult {
209+
const headers: Record<string, string | string[]> = {};
210+
for (const [key, value] of Object.entries(res.getHeaders())) {
211+
if (value !== undefined) {
212+
headers[key] = Array.isArray(value) ? value : String(value);
213+
}
214+
}
215+
for (const [key, value] of Object.entries(result.headers ?? {})) {
216+
headers[key] =
217+
key === 'set-cookie' ? [headers[key] ?? [], value].flat() : value;
218+
}
219+
return Object.keys(headers).length ? { ...result, headers } : result;
220+
}
221+
192222
function isJsonContentType(headers: HeaderBag): boolean {
193223
const contentType = headers['content-type'];
194224
const value = Array.isArray(contentType) ? contentType[0] : contentType;

0 commit comments

Comments
 (0)