Skip to content

Commit cc8546e

Browse files
authored
fix: override headers within req.rewrite() (#2189)
* fix: adding headers fix * chore: remove skip
1 parent 9c6ec9f commit cc8546e

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

cypress/e2e/middleware/enhanced.cy.ts

+6
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ describe('Enhanced middleware', () => {
1313
})
1414
})
1515

16+
it('passes in headers within request.rewrite()', () => {
17+
cy.request('/request-rewrite').then((response) => {
18+
expect(response.headers).to.have.property('x-rewrite-test', 'hello')
19+
})
20+
})
21+
1622
it('rewrites the response body using request.next()', () => {
1723
cy.visit('/static')
1824
cy.get('#message').contains('This was static (& escaping test &) but has been transformed in')

demos/middleware/middleware.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,13 @@ export async function middleware(req: NextRequest) {
4141
// skipMiddlewareUrlNormalize next config option is used so we have to try to match both html path and data blob path
4242
if (pathname.startsWith('/request-rewrite') || pathname.endsWith('/request-rewrite.json')) {
4343
// request.rewrite() should return the MiddlewareResponse object instead of the Response object.
44-
const res = await request.rewrite('/static-rewrite')
44+
const res = await request.rewrite('/static-rewrite',
45+
{
46+
headers: {
47+
'x-rewrite-test': 'hello',
48+
'x-rewrite-test-2': 'hello-2'
49+
}
50+
})
4551
const message = `This was static (& escaping test &) but has been transformed in ${req.geo?.city}`
4652

4753
// Transform the response HTML and props

packages/next/src/middleware/response.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ export class MiddlewareResponse extends NextResponse {
1111
private readonly dataTransforms: NextDataTransform[]
1212
private readonly elementHandlers: Array<[selector: string, handlers: ElementHandlers]>
1313

14-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
1514
constructor(public originResponse: Response, init?: ResponseInit) {
1615
// we need to propagate the set-cookie header, so response.cookies.get works correctly
1716
const initHeaders = new Headers()
@@ -23,6 +22,12 @@ export class MiddlewareResponse extends NextResponse {
2322
headers: initHeaders,
2423
})
2524

25+
if (init?.headers) {
26+
Object.entries(init.headers).forEach(([key, value]) => {
27+
this.headers.set(key, value)
28+
})
29+
}
30+
2631
// These are private in Node when compiling, but we access them in Deno at runtime
2732
Object.defineProperty(this, 'dataTransforms', {
2833
value: [],

0 commit comments

Comments
 (0)