diff --git a/edge-runtime/lib/response.ts b/edge-runtime/lib/response.ts index 8faf0d906a..ec0730e8ce 100644 --- a/edge-runtime/lib/response.ts +++ b/edge-runtime/lib/response.ts @@ -14,6 +14,8 @@ import { normalizeLocalePath, normalizeTrailingSlash, relativizeURL, + removeBasePath, + rewriteDataPath, } from './util.ts' export interface FetchEventResult { @@ -180,14 +182,16 @@ export const buildResponse = async ({ } if (isDataReq) { - // The rewrite target is a data request, but a middleware rewrite target is always for the page route, - // so we need to tell the server this is a data request. Setting the `x-nextjs-data` header is not enough. 🤷 - rewriteUrl.searchParams.set('__nextDataReq', '1') + rewriteUrl.pathname = rewriteDataPath({ + dataUrl: new URL(request.url).pathname, + newRoute: removeBasePath(rewriteUrl.pathname, nextConfig?.basePath), + basePath: nextConfig?.basePath, + }) + } else { + // respect trailing slash rules to prevent 308s + rewriteUrl.pathname = normalizeTrailingSlash(rewriteUrl.pathname, nextConfig?.trailingSlash) } - // respect trailing slash rules to prevent 308s - rewriteUrl.pathname = normalizeTrailingSlash(rewriteUrl.pathname, nextConfig?.trailingSlash) - const target = normalizeLocalizedTarget({ target: rewriteUrl.toString(), request, nextConfig }) if (target === request.url) { logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url') diff --git a/src/run/handlers/server.ts b/src/run/handlers/server.ts index 51cfb0290d..436411c812 100644 --- a/src/run/handlers/server.ts +++ b/src/run/handlers/server.ts @@ -83,15 +83,6 @@ export default async (request: Request) => { }, }) - if (new URL(request.url).searchParams.get('__nextDataReq')) { - const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta') - // @ts-expect-error NEXT_REQUEST_META doesn't exist in IncomingMessage type - const meta = req[NEXT_REQUEST_META] ?? {} - meta.isNextDataReq = true - // @ts-expect-error NEXT_REQUEST_META doesn't exist in IncomingMessage type - req[NEXT_REQUEST_META] = meta - } - disableFaultyTransferEncodingHandling(res as unknown as ComputeJsOutgoingMessage) const requestContext = getRequestContext() ?? createRequestContext() diff --git a/tests/e2e/edge-middleware.test.ts b/tests/e2e/edge-middleware.test.ts index 998eb8aff4..8b32fbaa10 100644 --- a/tests/e2e/edge-middleware.test.ts +++ b/tests/e2e/edge-middleware.test.ts @@ -54,14 +54,11 @@ test('it should render OpenGraph image meta tag correctly', async ({ page, middl }) test('json data rewrite works', async ({ middlewarePages }) => { - const response = await fetch( - `${middlewarePages.url}/_next/data/build-id/sha.json?__nextDataReq=1`, - { - headers: { - 'x-nextjs-data': '1', - }, + const response = await fetch(`${middlewarePages.url}/_next/data/build-id/sha.json`, { + headers: { + 'x-nextjs-data': '1', }, - ) + }) expect(response.ok).toBe(true) const body = await response.text()