Unverified Commit 9c120306 authored by Jude Gao's avatar Jude Gao Committed by GitHub

Fix RSC hash validation for middleware external rewrites (#82176)

parent 1b2e69fd
......@@ -19,6 +19,7 @@ import {
FLIGHT_HEADERS,
NEXT_REWRITTEN_PATH_HEADER,
NEXT_REWRITTEN_QUERY_HEADER,
NEXT_RSC_UNION_QUERY,
RSC_HEADER,
} from '../../client/components/app-router-headers'
import { ensureInstrumentationRegistered } from './globals'
......@@ -166,6 +167,8 @@ export async function adapter(
? new URL(params.request.url)
: requestURL
const rscHash = normalizeURL.searchParams.get(NEXT_RSC_UNION_QUERY)
const request = new NextRequestHint({
page: params.page,
// Strip internal query parameters off the request.
......@@ -397,6 +400,24 @@ export async function adapter(
}
}
/**
* Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,
* unless it's already present. This is necessary to ensure that RSC hash validation
* works correctly after a rewrite. For internal rewrites, the server can validate the
* RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical.
* However, for external rewrites (where the request is proxied to another Next.js server),
* the external server does not have access to the original URL or its search parameters.
* In these cases, forwarding the `_rsc` parameter is essential so that the external server
* can perform the correct RSC hash validation.
*/
if (response && rewrite && isRSCRequest && rscHash) {
const rewriteURL = new URL(rewrite)
if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) {
rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash)
response.headers.set('x-middleware-rewrite', rewriteURL.toString())
}
}
/**
* For redirects we will not include the locale in case when it is the
* default and we must also make sure the outgoing URL is a data one if
......
......@@ -7,7 +7,6 @@ import {
edgeSandboxNextRequestContext,
} from './context'
import { requestToBodyStream } from '../../body-streams'
import { NEXT_RSC_UNION_QUERY } from '../../../client/components/app-router-headers'
import type { ServerComponentsHmrCache } from '../../response-cache'
import {
getBuiltinRequestContext,
......@@ -117,7 +116,6 @@ export const run = withTaggedErrors(async function runWithTaggedErrors(params) {
const KUint8Array = runtime.evaluate('Uint8Array')
const urlInstance = new URL(params.request.url)
urlInstance.searchParams.delete(NEXT_RSC_UNION_QUERY)
params.request.url = urlInstance.toString()
......
// This page won't actually be served due to middleware rewrite
export default function AboutPage() {
return (
<div>
<h1>About Page (This should not be seen)</h1>
<p>This page should be rewritten to external server</p>
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Home Page</h1>
<div id="home-content">
<p>This is the home page</p>
<Link href="/about" id="about-link">
Go to About Page
</Link>
</div>
</div>
)
}
import { createServer } from 'node:http'
let receivedRequests = []
function createExternalServer() {
const server = createServer((req, res) => {
const requestUrl = `${req.url}`
console.log('External server received request:', requestUrl)
// Store the request for testing
receivedRequests.push({
url: requestUrl,
method: req.method,
headers: req.headers,
timestamp: Date.now(),
})
// Simple response
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(`
<html>
<body>
<h1>External Server Response</h1>
<p>Request URL: ${requestUrl}</p>
<div id="external-response">External server handled the request</div>
</body>
</html>
`)
})
return server
}
export async function startExternalServer(port) {
receivedRequests = [] // Reset requests
const server = createExternalServer()
const cleanup = async () => {
await new Promise((resolve) => server.close(resolve))
}
return new Promise((resolve, reject) => {
server.on('error', reject)
server.listen(port, () => {
console.log('External server listening on port', port)
resolve({ cleanup, getReceivedRequests: () => receivedRequests })
})
})
}
import webdriver from 'next-webdriver'
import { findPort, nextBuild, nextStart } from 'next-test-utils'
import { isNextDeploy, isNextDev } from 'e2e-utils'
import { startExternalServer } from './external-server.mjs'
describe('middleware RSC external rewrite', () => {
if (isNextDev || isNextDeploy) {
test('should not run during dev or deploy test runs', () => {})
return
}
let cleanup: () => Promise<void>
let nextPort: number
let externalServerManager: {
cleanup: () => Promise<void>
getReceivedRequests: () => any[]
}
beforeAll(async () => {
const appDir = __dirname
await nextBuild(appDir, undefined, { cwd: appDir })
// Start external server first
const externalPort = await findPort()
process.env.EXTERNAL_SERVER_PORT = externalPort.toString()
externalServerManager = await startExternalServer(externalPort)
// Start Next.js server
nextPort = await findPort()
const nextApp = await nextStart(appDir, nextPort, {
env: {
...process.env,
EXTERNAL_SERVER_PORT: externalPort.toString(),
},
})
cleanup = async () => {
await nextApp.kill()
await externalServerManager.cleanup()
}
})
afterAll(async () => {
if (cleanup) {
await cleanup()
}
})
test('should forward _rsc parameter to external server on RSC navigation', async () => {
let browser
try {
browser = await webdriver(nextPort, '/')
// Verify we're on the home page
const homeContent = await browser.elementById('home-content')
expect(await homeContent.text()).toContain('This is the home page')
// Clear any previous requests
const initialRequests = externalServerManager.getReceivedRequests()
console.log('Initial requests before navigation:', initialRequests.length)
// Click the link to /about which should trigger RSC navigation
const aboutLink = await browser.elementById('about-link')
await aboutLink.click()
// Wait a bit for the request to be processed
await browser.waitForElementByCss('#external-response', 5000)
// Check that external server received the request
const receivedRequests = externalServerManager.getReceivedRequests()
console.log('Total requests received:', receivedRequests.length)
console.log(
'Received requests:',
receivedRequests.map((r) => ({ url: r.url, method: r.method }))
)
// Find requests that contain _rsc parameter
const rscRequests = receivedRequests.filter((req) =>
req.url.includes('_rsc=')
)
console.log(
'RSC requests:',
rscRequests.map((r) => r.url)
)
// Verify that at least one request contains the _rsc parameter
expect(rscRequests.length).toBeGreaterThan(0)
// Verify the external server response is displayed
const externalResponse = await browser.elementById('external-response')
expect(await externalResponse.text()).toBe(
'External server handled the request'
)
} finally {
if (browser) {
await browser.close()
}
}
})
})
import { NextRequest, NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone()
if (url.pathname === '/about') {
// Get the external server port from environment or default
const externalPort = process.env.EXTERNAL_SERVER_PORT || '3001'
const externalUrl = `http://localhost:${externalPort}/about`
console.log('Middleware rewriting /about to:', externalUrl)
// Rewrite to external server
return NextResponse.rewrite(externalUrl)
}
return NextResponse.next()
}
export const config = {
matcher: ['/about'],
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
logging: {
level: 'verbose',
},
},
}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment