diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts index 1c2933e1eccc..fd3e99692d08 100644 --- a/packages/astro/src/server/middleware.ts +++ b/packages/astro/src/server/middleware.ts @@ -97,6 +97,7 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareResponseH }, async span => { const originalResponse = await next(); + if (span && originalResponse.status) { span.setHttpStatus(originalResponse.status); } @@ -110,13 +111,11 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareResponseH return originalResponse; } - const { body, ...restOfOriginalResponse } = originalResponse; - // Type case necessary b/c the body's ReadableStream type doesn't include // the async iterator that is actually available in Node // We later on use the async iterator to read the body chunks // see https://github.com/microsoft/TypeScript/issues/39051 - const originalBody = body as NodeJS.ReadableStream | null; + const originalBody = originalResponse.body as NodeJS.ReadableStream | null; if (!originalBody) { return originalResponse; } @@ -126,13 +125,13 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareResponseH for await (const chunk of originalBody) { const html = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk); const modifiedHtml = addMetaTagToHead(html, hub, span); - controller.enqueue(modifiedHtml); + controller.enqueue(new TextEncoder().encode(modifiedHtml)); } controller.close(); }, }); - return new Response(newResponseStream, restOfOriginalResponse); + return new Response(newResponseStream, originalResponse); }, ); return res; diff --git a/packages/astro/test/server/middleware.test.ts b/packages/astro/test/server/middleware.test.ts index 9be67cc481a0..058982f06cc6 100644 --- a/packages/astro/test/server/middleware.test.ts +++ b/packages/astro/test/server/middleware.test.ts @@ -259,7 +259,8 @@ describe('sentryMiddleware', () => { url: new URL('https://myDomain.io/users/'), }; - const originalResponse = new Response('

no head

', { + const originalHtml = '

no head

'; + const originalResponse = new Response(originalHtml, { headers: new Headers({ 'content-type': 'text/html' }), }); const next = vi.fn(() => Promise.resolve(originalResponse)); @@ -267,7 +268,11 @@ describe('sentryMiddleware', () => { // @ts-expect-error, a partial ctx object is fine here const resultFromNext = await middleware(ctx, next); - expect(resultFromNext).toBe(originalResponse); + expect(resultFromNext?.headers.get('content-type')).toEqual('text/html'); + + const html = await resultFromNext?.text(); + + expect(html).toBe(originalHtml); }); });