Unverified Commit 48acc479 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure basePath behavior with GS(S)P redirect (#18988)

This ensures we match the `basePath` handling for redirects in `next.config.js` with redirects from `getStaticProps` and `getServerSideProps` and also adds a separate test suite to ensure GS(S)P redirects with `basePath` work correctly

Fixes: https://github.com/vercel/next.js/issues/18984
Closes: https://github.com/vercel/next.js/pull/18892
parent a429a47f
......@@ -824,10 +824,15 @@ const nextServerlessLoader: loader.Loader = function () {
} else if (renderOpts.isRedirect && !_nextData) {
const redirect = {
destination: renderOpts.pageData.pageProps.__N_REDIRECT,
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS,
basePath: renderOpts.pageData.pageProps.__N_REDIRECT_BASE_PATH
}
const statusCode = getRedirectStatus(redirect)
if ("${basePath}" && redirect.basePath !== false) {
redirect.destination = \`${basePath}\${redirect.destination}\`
}
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader('Refresh', \`0;url=\${redirect.destination}\`)
}
......
......@@ -11,17 +11,20 @@ export type Rewrite = {
basePath?: false
}
export type Redirect = Rewrite & {
statusCode?: number
permanent?: boolean
}
export type Header = {
source: string
basePath?: false
headers: Array<{ key: string; value: string }>
}
// internal type used for validation (not user facing)
export type Redirect = Rewrite & {
statusCode?: number
permanent?: boolean
destination: string
basePath?: false
}
export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
export function getRedirectStatus(route: {
......
......@@ -815,10 +815,15 @@ export default class Router implements BaseRouter {
// it's not
if (destination.startsWith('/')) {
const parsedHref = parseRelativeUrl(destination)
this._resolveHref(parsedHref, pages)
this._resolveHref(parsedHref, pages, false)
if (pages.includes(parsedHref.pathname)) {
return this.change(method, destination, destination, options)
const { url: newUrl, as: newAs } = prepareUrlAs(
this,
destination,
destination
)
return this.change(method, newUrl, newAs, options)
}
}
......
......@@ -1271,8 +1271,14 @@ export default class Server {
const redirect = {
destination: pageData.pageProps.__N_REDIRECT,
statusCode: pageData.pageProps.__N_REDIRECT_STATUS,
basePath: pageData.pageProps.__N_REDIRECT_BASE_PATH,
}
const statusCode = getRedirectStatus(redirect)
const { basePath } = this.nextConfig
if (basePath && redirect.basePath !== false) {
redirect.destination = `${basePath}${redirect.destination}`
}
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader('Refresh', `0;url=${redirect.destination}`)
......
......@@ -53,6 +53,7 @@ import optimizeAmp from './optimize-amp'
import {
allowedStatusCodes,
getRedirectStatus,
Redirect,
} from '../../lib/load-custom-routes'
function noRouter() {
......@@ -290,18 +291,12 @@ const invalidKeysMsg = (methodName: string, invalidKeys: string[]) => {
)
}
type Redirect = {
permanent: boolean
destination: string
statusCode?: number
}
function checkRedirectValues(
redirect: Redirect,
req: IncomingMessage,
method: 'getStaticProps' | 'getServerSideProps'
) {
const { destination, permanent, statusCode } = redirect
const { destination, permanent, statusCode, basePath } = redirect
let errors: string[] = []
const hasStatusCode = typeof statusCode !== 'undefined'
......@@ -326,6 +321,14 @@ function checkRedirectValues(
)
}
const basePathType = typeof basePath
if (basePathType !== 'undefined' && basePathType !== 'boolean') {
errors.push(
`\`basePath\` should be undefined or a false, received ${basePathType}`
)
}
if (errors.length > 0) {
throw new Error(
`Invalid redirect object returned from ${method} for ${req.url}\n` +
......@@ -657,7 +660,7 @@ export async function renderToHTML(
data.redirect &&
typeof data.redirect === 'object'
) {
checkRedirectValues(data.redirect, req, 'getStaticProps')
checkRedirectValues(data.redirect as Redirect, req, 'getStaticProps')
if (isBuildTimeSSG) {
throw new Error(
......@@ -670,6 +673,9 @@ export async function renderToHTML(
__N_REDIRECT: data.redirect.destination,
__N_REDIRECT_STATUS: getRedirectStatus(data.redirect),
}
if (typeof data.redirect.basePath !== 'undefined') {
;(data as any).props.__N_REDIRECT_BASE_PATH = data.redirect.basePath
}
;(renderOpts as any).isRedirect = true
}
......@@ -791,11 +797,18 @@ export async function renderToHTML(
}
if ('redirect' in data && typeof data.redirect === 'object') {
checkRedirectValues(data.redirect, req, 'getServerSideProps')
checkRedirectValues(
data.redirect as Redirect,
req,
'getServerSideProps'
)
;(data as any).props = {
__N_REDIRECT: data.redirect.destination,
__N_REDIRECT_STATUS: getRedirectStatus(data.redirect),
}
if (typeof data.redirect.basePath !== 'undefined') {
;(data as any).props.__N_REDIRECT_BASE_PATH = data.redirect.basePath
}
;(renderOpts as any).isRedirect = true
}
......
......@@ -37,6 +37,18 @@ declare module 'react' {
}
}
export type Redirect =
| {
statusCode: 301 | 302 | 303 | 307 | 308
destination: string
basePath?: false
}
| {
permanent: boolean
destination: string
basePath?: false
}
/**
* `Page` type, use it as a guide to create `pages`.
*/
......@@ -72,11 +84,6 @@ export {
NextApiHandler,
}
type Redirect = {
permanent: boolean
destination: string
}
export type GetStaticPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery> = {
params?: Q
preview?: boolean
......
module.exports = {
basePath: '/docs',
}
export default function NotFound() {
return <p>oops not found</p>
}
export default function Another() {
return <p id="another">another Page</p>
}
import { useRouter } from 'next/router'
export default function Post(props) {
const router = useRouter()
if (typeof window === 'undefined') {
if (router.query.post?.startsWith('redir')) {
console.log(router)
throw new Error('render should not occur for redirect')
}
}
if (typeof window !== 'undefined' && !window.initialHref) {
window.initialHref = window.location.href
}
if (router.isFallback) return <p>Loading...</p>
return (
<>
<p id="gsp">getStaticProps</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export const getStaticProps = ({ params }) => {
if (params.post.startsWith('redir')) {
let destination = '/404'
if (params.post.includes('dest-')) {
destination = params.post.split('dest-').pop().replace(/_/g, '/')
}
let permanent = undefined
let statusCode = undefined
if (params.post.includes('statusCode-')) {
permanent = parseInt(
params.post.split('statusCode-').pop().split('-').shift(),
10
)
}
if (params.post.includes('permanent')) {
permanent = true
} else if (!statusCode) {
permanent = false
}
const redirect = {
destination,
permanent,
statusCode,
}
if (params.post.includes('no-basepath-')) {
redirect.basePath = false
}
return { redirect }
}
return {
props: {
params,
},
}
}
export const getStaticPaths = () => {
return {
paths: ['first', 'second'].map((post) => ({ params: { post } })),
fallback: true,
}
}
import { useRouter } from 'next/router'
export default function Post(props) {
const router = useRouter()
if (typeof window === 'undefined') {
if (router.query.post?.startsWith('redir')) {
console.log(router)
throw new Error('render should not occur for redirect')
}
}
return (
<>
<p id="gssp">getServerSideProps</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export const getServerSideProps = ({ params }) => {
if (params.post.startsWith('redir')) {
let destination = '/404'
if (params.post.includes('dest-')) {
destination = params.post.split('dest-').pop().replace(/_/g, '/')
}
let permanent = undefined
let statusCode = undefined
if (params.post.includes('statusCode-')) {
statusCode = parseInt(
params.post.split('statusCode-').pop().split('-').shift(),
10
)
}
if (params.post.includes('permanent')) {
permanent = true
} else if (!statusCode) {
permanent = false
}
const redirect = {
destination,
permanent,
statusCode,
}
if (params.post.includes('no-basepath-')) {
redirect.basePath = false
}
return { redirect }
}
return {
props: {
params,
},
}
}
export default function Index() {
if (typeof window !== 'undefined' && !window.initialHref) {
window.initialHref = window.location.href
}
return <p id="index">Index Page</p>
}
This diff is collapsed.
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