Skip to content

fix: Return MiddlewareResponse obj for rewrite #2159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Jun 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion cypress/e2e/middleware/enhanced.cy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
describe('Enhanced middleware', () => {
it('rewrites the response body', () => {
it('rewrites the response body using request.rewrite()', () => {
cy.visit('/request-rewrite')
cy.get('#message').contains('This was static (& escaping test &) but has been transformed in')
cy.contains("This is an ad that isn't shown by default")
})

it('modifies the page props when using request.rewrite()', () => {
cy.visit('/request-rewrite')
cy.get('script#__NEXT_DATA__').then((element) => {
const { props } = JSON.parse(element.text());
expect(props.pageProps.message).to.include('This was static (& escaping test &) but has been transformed in')
})
})

it('rewrites the response body using request.next()', () => {
cy.visit('/static')
cy.get('#message').contains('This was static (& escaping test &) but has been transformed in')
cy.contains("This is an ad that isn't shown by default")
Expand Down
18 changes: 17 additions & 1 deletion demos/middleware/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,22 @@ export async function middleware(req: NextRequest) {
const message = `This was static (& escaping test &) but has been transformed in ${req.geo?.city}`

// Transform the response HTML and props
res.replaceText('p[id=message]', message)
res.replaceText('#message', message)
res.setPageProp('message', message)
res.setPageProp('showAd', true)

res.headers.set('x-modified-edge', 'true')
res.headers.set('x-is-deno', 'Deno' in globalThis ? 'true' : 'false')
return res
}

if (pathname.startsWith('/request-rewrite')) {
// request.rewrite() should return the MiddlewareResponse object instead of the Response object.
const res = await request.rewrite('/static-rewrite')
const message = `This was static (& escaping test &) but has been transformed in ${req.geo?.city}`

// Transform the response HTML and props
res.replaceText('#message', message)
res.setPageProp('message', message)
res.setPageProp('showAd', true)

Expand Down Expand Up @@ -138,6 +153,7 @@ export const config = {
'/headers',
'/cookies/:path*',
{ source: '/static' },
{source: '/request-rewrite' },
{ source: '/matcher-cookie'},
{ source: '/shows/((?!99|88).*)' },
{
Expand Down
10 changes: 10 additions & 0 deletions demos/middleware/pages/request-rewrite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const Rewrite = () => {
return (
<div>
<p>This should have been rewritten</p>
</div>
)
}

export default Rewrite

37 changes: 37 additions & 0 deletions demos/middleware/pages/static-rewrite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import * as React from 'react'

const useHydrated = () => {
const [hydrated, setHydrated] = React.useState(false)
React.useEffect(() => {
setHydrated(true)
}, [])
return hydrated
}

const Page = ({ message, showAd }) => {
const hydrated = useHydrated()
return (
<div>
<p id="message">{message}</p>
{hydrated && showAd ? (
<div>
<p>This is an ad that isn't shown by default on static test 2 page</p>
<img src="http://placekitten.com/400/300" />
</div>
) : (
<p>No ads for me</p>
)}
</div>
)
}

export async function getStaticProps() {
return {
props: {
message: 'This is a static page',
showAd: false,
},
}
}

export default Page
8 changes: 4 additions & 4 deletions packages/next/src/middleware/request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { Context } from '@netlify/edge-functions'
import type { NextURL } from 'next/dist/server/web/next-url'
import { NextResponse } from 'next/server'
import type { NextRequest as InternalNextRequest } from 'next/server'

import { MiddlewareResponse } from './response'
Expand Down Expand Up @@ -64,16 +63,17 @@ export class MiddlewareRequest extends Request {
if (response.status === 301 && locationHeader?.startsWith('/')) {
response = await this.context.rewrite(locationHeader)
}

return new MiddlewareResponse(response)
}

rewrite(destination: string | URL | NextURL, init?: ResponseInit): NextResponse {
async rewrite(destination: string | URL | NextURL, init?: ResponseInit) {
if (typeof destination === 'string' && destination.startsWith('/')) {
destination = new URL(destination, this.url)
}
this.applyHeaders()
return NextResponse.rewrite(destination, init)
const response = await this.context.rewrite(destination)

return new MiddlewareResponse(response, init)
}

get headers() {
Expand Down
4 changes: 3 additions & 1 deletion packages/next/src/middleware/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export type NextDataTransform = <T extends { pageProps?: Record<string, any> }>(
export class MiddlewareResponse extends NextResponse {
private readonly dataTransforms: NextDataTransform[]
private readonly elementHandlers: Array<[selector: string, handlers: ElementHandlers]>
constructor(public originResponse: Response) {

// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(public originResponse: Response, init?: ResponseInit) {
// we need to propagate the set-cookie header, so response.cookies.get works correctly
const initHeaders = new Headers()
if (originResponse.headers.has('set-cookie')) {
Expand Down
12 changes: 6 additions & 6 deletions test/e2e/next-test-lib/next-test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import spawn from 'cross-spawn'
import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs'
import { writeFile } from 'fs-extra'
import { fetch as undiciFetch } from 'undici'
import { fetch as undiciFetch } from 'next/dist/compiled/undici'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we never figured out why the undici dep was no longer included?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It happened here c295bc2
it got removed from package-lock but it looks like it was not set as a dep in the package.json.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once we move to Node.js 18, fetch is native, so this import won't be required.

import nodeFetch from 'node-fetch'
import path from 'path'
import qs from 'querystring'
Expand Down Expand Up @@ -111,7 +111,7 @@ async function processChunkedResponse(response) {
* @param {string | number} appPort
* @param {string} pathname
* @param {Record<string, any> | string | undefined} [query]
* @param {import("undici").RequestInit} [opts]
* @param {import("next/dist/compiled/undici").RequestInit} [opts]
* @returns {Promise<string>}
*/
export function renderViaHTTP(appPort, pathname, query, opts) {
Expand All @@ -121,11 +121,11 @@ export function renderViaHTTP(appPort, pathname, query, opts) {
/**
* @param {string | number} appPort
* @param {string} pathname
* @param {Record<string, any> | string | undefined} query
* @param {RequestInit} opts
* @returns {Promise<Response>}
* @param {Record<string, any> | string | null | undefined} [query]
* @param {import('node-fetch').RequestInit} [opts]
* @returns {Promise<Response & {buffer: any} & {headers: Headers}>}
*/
export async function fetchViaHTTP(appPort, pathname, query = undefined, opts = undefined, useUndici = false) {
export function fetchViaHTTP(appPort, pathname, query, opts, useUndici = false) {
const url = `${pathname}${typeof query === 'string' ? query : query ? `?${qs.stringify(query)}` : ''}`
const fetch = useUndici ? undiciFetch : nodeFetch
const fullUrl = getFullUrl(appPort, url)
Expand Down