Handle basePath for redirect() (#54277)

### What & Why
Add base path handling for the url in redirect error if the `basePath` is configured.

This is only break for server rendering case as the `basePath` is missing in the `Location` header. When running `next build`, everything is managed well with app router and base path on client side so it didn't break.

### How

Adding `basePath` if it's presented for `Location` header.
Update the `RenderOpts` type as basePath is already passed down in it, also update them for turbopack entries

Fixes #54163
Closes NEXT-1529
This commit is contained in:
Jiachi Liu 2023-08-20 05:32:52 +02:00 committed by GitHub
parent 311eea4c6a
commit f2a3fd9fc3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 23 additions and 1 deletions

View file

@ -73,6 +73,7 @@ async function runOperation(renderData: RenderData) {
} = {
// TODO: give an actual buildId when next build is supported
buildId: 'development',
basePath: '',
params: renderData.params,
supportsDynamicHTML: true,
dev: true,

View file

@ -29,6 +29,7 @@ async function render(request: NextRequest, event: NextFetchEvent) {
supportsDynamicHTML: true,
dev: true,
buildId: 'development',
basePath: '',
buildManifest: {
polyfillFiles: [],
rootMainFiles: BOOTSTRAP.filter((path) => path.endsWith('.js')),

View file

@ -77,6 +77,7 @@ import { warn } from '../../build/output/log'
import { appendMutableCookies } from '../web/spec-extension/adapters/request-cookies'
import { createServerInsertedHTML } from './server-inserted-html'
import { getRequiredScripts } from './required-scripts'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug]
@ -1576,7 +1577,11 @@ export async function renderToHTMLOrFlight(
res.setHeader('set-cookie', Array.from(headers.values()))
}
}
res.setHeader('Location', getURLFromRedirectError(err))
const redirectUrl = addPathPrefix(
getURLFromRedirectError(err),
renderOpts.basePath
)
res.setHeader('Location', redirectUrl)
}
const is404 = res.statusCode === 404

View file

@ -124,6 +124,7 @@ export type RenderOptsPartial = {
err?: Error | null
dev?: boolean
buildId: string
basePath: string
clientReferenceManifest?: ClientReferenceManifest
supportsDynamicHTML: boolean
runtime?: ServerRuntime

View file

@ -0,0 +1,5 @@
import { redirect } from 'next/navigation'
export default function Page() {
redirect('/another')
}

View file

@ -1,4 +1,5 @@
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app dir basepath',
@ -34,5 +35,13 @@ createNextDescribe(
expect(ogImageHref).toContain('/base/another/opengraph-image.png')
})
it('should prefix redirect() with basePath', async () => {
const browser = await next.browser('/base/redirect')
await check(async () => {
expect(await browser.url()).toBe(`${next.url}/base/another`)
return 'success'
}, 'success')
})
}
)