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>
}
/* eslint-env jest */
import http from 'http'
import url from 'url'
import fs from 'fs-extra'
import webdriver from 'next-webdriver'
import { join } from 'path'
import {
findPort,
launchApp,
killApp,
nextBuild,
nextStart,
fetchViaHTTP,
check,
File,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '..')
const nextConfig = new File(join(appDir, 'next.config.js'))
let app
let appPort
const basePath = '/docs'
const runTests = (isDev) => {
it('should apply temporary redirect when visited directly for GSSP page', async () => {
const res = await fetchViaHTTP(
appPort,
`${basePath}/gssp-blog/redirect-1`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe(`${basePath}/404`)
})
it('should apply temporary redirect when visited directly basePath false for GSSP page', async () => {
const res = await fetchViaHTTP(
appPort,
`${basePath}/gssp-blog/redirect-1-no-basepath-`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe(`/404`)
})
it('should apply permanent redirect when visited directly for GSSP page', async () => {
const res = await fetchViaHTTP(
appPort,
`${basePath}/gssp-blog/redirect-permanent`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(308)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe(`${basePath}/404`)
expect(res.headers.get('refresh')).toContain(`url=${basePath}/404`)
})
it('should apply statusCode 301 redirect when visited directly for GSSP page', async () => {
const res = await fetchViaHTTP(
appPort,
`${basePath}/gssp-blog/redirect-statusCode-301`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(301)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe(`${basePath}/404`)
expect(res.headers.get('refresh')).toBe(null)
})
it('should apply statusCode 303 redirect when visited directly for GSSP page', async () => {
const res = await fetchViaHTTP(
appPort,
`${basePath}/gssp-blog/redirect-statusCode-303`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(303)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe(`${basePath}/404`)
expect(res.headers.get('refresh')).toBe(null)
})
it('should apply redirect when fallback GSP page is visited directly (internal dynamic)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/gsp-blog/redirect-dest-_gsp-blog_first`,
true,
true
)
await browser.waitForElementByCss('#gsp')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props).toEqual({
params: {
post: 'first',
},
})
const initialHref = await browser.eval(() => window.initialHref)
const { pathname } = url.parse(initialHref)
expect(pathname).toBe(`${basePath}/gsp-blog/redirect-dest-_gsp-blog_first`)
})
if (!isDev) {
it('should apply redirect when fallback GSP page is visited directly (internal dynamic) 2nd visit', async () => {
const browser = await webdriver(
appPort,
`${basePath}/gsp-blog/redirect-dest-_gsp-blog_first`,
true,
true
)
await browser.waitForElementByCss('#gsp')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props).toEqual({
params: {
post: 'first',
},
})
const initialHref = await browser.eval(() => window.initialHref)
const { pathname } = url.parse(initialHref)
// since it was cached the initial value is now the redirect
// result
expect(pathname).toBe(`${basePath}/gsp-blog/first`)
})
}
it('should apply redirect when fallback GSP page is visited directly (internal normal)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/gsp-blog/redirect-dest-_`,
true,
true
)
await browser.waitForElementByCss('#index')
const initialHref = await browser.eval(() => window.initialHref)
const { pathname } = url.parse(initialHref)
expect(pathname).toBe(`${basePath}/gsp-blog/redirect-dest-_`)
})
if (!isDev) {
it('should apply redirect when fallback GSP page is visited directly (internal normal) 2nd visit', async () => {
const browser = await webdriver(
appPort,
`${basePath}/gsp-blog/redirect-dest-_`,
true,
true
)
await browser.waitForElementByCss('#index')
const initialHref = await browser.eval(() => window.initialHref)
const { pathname } = url.parse(initialHref)
expect(pathname).toBe(`${basePath}`)
})
}
it('should apply redirect when fallback GSP page is visited directly (external)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/gsp-blog/redirect-dest-_missing`,
true,
true
)
await check(
() => browser.eval(() => document.documentElement.innerHTML),
/oops not found/
)
const initialHref = await browser.eval(() => window.initialHref)
expect(initialHref).toBe(null)
const curUrl = await browser.url()
const { pathname } = url.parse(curUrl)
expect(pathname).toBe('/missing')
})
it('should apply redirect when GSSP page is navigated to client-side (internal dynamic)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/gssp-blog/redirect-dest-_gssp-blog_first`,
true,
true
)
await browser.waitForElementByCss('#gssp')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props).toEqual({
params: {
post: 'first',
},
})
})
it('should apply redirect when GSSP page is navigated to client-side (internal normal)', async () => {
const browser = await webdriver(appPort, `${basePath}`, true, true)
await browser.eval(`(function () {
window.next.router.push('/gssp-blog/redirect-dest-_another')
})()`)
await browser.waitForElementByCss('#another')
const text = await browser.elementByCss('#another').text()
expect(text).toEqual('another Page')
})
it('should apply redirect when GSSP page is navigated to client-side (external)', async () => {
const browser = await webdriver(appPort, `${basePath}`, true, true)
await browser.eval(`(function () {
window.next.router.push('/gssp-blog/redirect-dest-_gssp-blog_first')
})()`)
await browser.waitForElementByCss('#gssp')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props).toEqual({
params: {
post: 'first',
},
})
})
it('should apply redirect when GSP page is navigated to client-side (internal)', async () => {
const browser = await webdriver(appPort, `${basePath}`, true, true)
await browser.eval(`(function () {
window.next.router.push('/gsp-blog/redirect-dest-_another')
})()`)
await browser.waitForElementByCss('#another')
const text = await browser.elementByCss('#another').text()
expect(text).toEqual('another Page')
})
it('should apply redirect when GSP page is navigated to client-side (external)', async () => {
const browser = await webdriver(appPort, `${basePath}`, true, true)
await browser.eval(`(function () {
window.next.router.push('/gsp-blog/redirect-dest-_gsp-blog_first')
})()`)
await browser.waitForElementByCss('#gsp')
const props = JSON.parse(await browser.elementByCss('#props').text())
expect(props).toEqual({
params: {
post: 'first',
},
})
})
it('should not replace history of the origin page when GSSP page is navigated to client-side (internal normal)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/another?mark_as=root`,
true,
true
)
await browser.eval(`(function () {
window.next.router.push('/')
})()`)
await browser.waitForElementByCss('#index')
await browser.eval(`(function () {
window.next.router.push('/gssp-blog/redirect-dest-_another')
})()`)
await browser.waitForElementByCss('#another')
await browser.eval(`(function () {
window.history.back()
})()`)
const curUrl = await browser.url()
const { path } = url.parse(curUrl)
expect(path).toEqual(`${basePath}`)
})
it('should not replace history of the origin page when GSSP page is navigated to client-side (external)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/another?mark_as=root`,
true,
true
)
await browser.eval(`(function () {
window.next.router.push('/')
})()`)
await browser.waitForElementByCss('#index')
await browser.eval(`(function () {
window.next.router.push('/gssp-blog/redirect-dest-_gssp-blog_first')
})()`)
await browser.waitForElementByCss('#gssp')
await browser.eval(`(function () {
window.history.back()
})()`)
const curUrl = await browser.url()
const { path } = url.parse(curUrl)
expect(path).toEqual(`${basePath}`)
})
it('should not replace history of the origin page when GSP page is navigated to client-side (internal)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/another?mark_as=root`,
true,
true
)
await browser.eval(`(function () {
window.next.router.push('/')
})()`)
await browser.waitForElementByCss('#index')
await browser.eval(`(function () {
window.next.router.push('/gsp-blog/redirect-dest-_another')
})()`)
await browser.waitForElementByCss('#another')
await browser.eval(`(function () {
window.history.back()
})()`)
const curUrl = await browser.url()
const { path } = url.parse(curUrl)
expect(path).toEqual(`${basePath}`)
})
it('should not replace history of the origin page when GSP page is navigated to client-side (external)', async () => {
const browser = await webdriver(
appPort,
`${basePath}/another?mark_as=root`,
true,
true
)
await browser.eval(`(function () {
window.next.router.push('/')
})()`)
await browser.waitForElementByCss('#index')
await browser.eval(`(function () {
window.next.router.push('/gsp-blog/redirect-dest-_gsp-blog_first')
})()`)
await browser.waitForElementByCss('#gsp')
await browser.eval(`(function () {
window.history.back()
})()`)
const curUrl = await browser.url()
const { path } = url.parse(curUrl)
expect(path).toEqual(`${basePath}`)
})
}
describe('GS(S)P Redirect Support', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests(true)
})
describe('production mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('serverless mode', () => {
let server
beforeAll(async () => {
nextConfig.write(
`module.exports = {
basePath: "${basePath}",
target: 'experimental-serverless-trace'
}`
)
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
nextConfig.restore()
await killApp(app)
try {
server.close()
} catch (err) {
console.error('failed to close server', err)
}
})
it('should handle redirect in raw serverless mode correctly', async () => {
server = http.createServer(async (req, res) => {
try {
console.log(req.url)
if (req.url.includes('/gsp-blog')) {
await require(join(
appDir,
'.next/serverless/pages/gsp-blog/[post].js'
)).render(req, res)
} else {
await require(join(
appDir,
'./.next/serverless/pages/gssp-blog/[post].js'
)).render(req, res)
}
} catch (err) {
console.error('failed to render', err)
res.statusCode = 500
res.end('error')
}
})
const port = await findPort()
await new Promise((resolve, reject) => {
server.listen(port, (err) => (err ? reject(err) : resolve()))
})
console.log(`Raw serverless server listening at port ${port}`)
const res1 = await fetchViaHTTP(
port,
'/gsp-blog/redirect-dest-_gsp-blog_first',
undefined,
{
redirect: 'manual',
}
)
expect(res1.status).toBe(307)
const parsed = url.parse(res1.headers.get('location'), true)
expect(parsed.pathname).toBe(`${basePath}/gsp-blog/first`)
expect(parsed.query).toEqual({})
expect(res1.headers.get('refresh')).toBe(null)
const res2 = await fetchViaHTTP(
port,
'/gsp-blog/redirect-permanent-dest-_gsp-blog_first',
undefined,
{
redirect: 'manual',
}
)
expect(res2.status).toBe(308)
expect(res2.headers.get('refresh')).toContain(
`url=${basePath}/gsp-blog/first`
)
const parsed2 = url.parse(res2.headers.get('location'), true)
expect(parsed2.pathname).toBe(`${basePath}/gsp-blog/first`)
expect(parsed2.query).toEqual({})
const res3 = await fetchViaHTTP(
port,
'/gssp-blog/redirect-dest-_gssp-blog_first',
undefined,
{
redirect: 'manual',
}
)
expect(res3.status).toBe(307)
expect(res3.headers.get('refresh')).toBe(null)
const parsed3 = url.parse(res3.headers.get('location'), true)
expect(parsed3.pathname).toBe(`${basePath}/gssp-blog/first`)
expect(parsed3.query).toEqual({})
const res4 = await fetchViaHTTP(
port,
'/gssp-blog/redirect-permanent-dest-_gssp-blog_first',
undefined,
{
redirect: 'manual',
}
)
expect(res4.status).toBe(308)
expect(res4.headers.get('refresh')).toContain(
`url=${basePath}/gssp-blog/first`
)
const parsed4 = url.parse(res4.headers.get('location'), true)
expect(parsed4.pathname).toBe(`${basePath}/gssp-blog/first`)
expect(parsed4.query).toEqual({})
})
runTests()
})
it('should error for redirect during prerendering', async () => {
await fs.mkdirp(join(appDir, 'pages/invalid'))
await fs.writeFile(
join(appDir, 'pages', 'invalid', '[slug].js'),
`
export default function Post(props) {
return "hi"
}
export const getStaticProps = ({ params }) => {
return {
redirect: {
permanent: true,
destination: '/another'
}
}
}
export const getStaticPaths = () => {
return {
paths: ['first', 'second'].map((slug) => ({ params: { slug } })),
fallback: true,
}
}
`
)
const { stdout, stderr } = await nextBuild(appDir, undefined, {
stdout: true,
stderr: true,
})
const output = stdout + stderr
await fs.remove(join(appDir, 'pages/invalid'))
expect(output).toContain(
'`redirect` can not be returned from getStaticProps during prerendering'
)
})
})
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