Unverified Commit c8d26edf authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Allow passing statusCode for GS(S)P redirect (#18422)

This adds support for passing `statusCode` in a `redirect` from `getServerSideProps` or `getStaticProps` which matches the `redirect` shape allowed to be returned for `redirects` in `next.config.js`

Closes: https://github.com/vercel/next.js/issues/18350
parent d07b25a9
...@@ -63,7 +63,7 @@ The `context` parameter is an object containing the following keys: ...@@ -63,7 +63,7 @@ The `context` parameter is an object containing the following keys:
- `props` - A **required** object with the props that will be received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) - `props` - A **required** object with the props that will be received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization)
- `revalidate` - An **optional** amount in seconds after which a page re-generation can occur. More on [Incremental Static Regeneration](#incremental-static-regeneration) - `revalidate` - An **optional** amount in seconds after which a page re-generation can occur. More on [Incremental Static Regeneration](#incremental-static-regeneration)
- `notFound` - An optional boolean value to allow the page to return a 404 status and page. More on [Incremental Static Regeneration](#incremental-static-regeneration) - `notFound` - An optional boolean value to allow the page to return a 404 status and page. More on [Incremental Static Regeneration](#incremental-static-regeneration)
- `redirect` - An optional redirect value to allow redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }` - `redirect` - An optional redirect value to allow redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both.
> **Note**: You can import modules in top-level scope for use in `getStaticProps`. > **Note**: You can import modules in top-level scope for use in `getStaticProps`.
> Imports used in `getStaticProps` will [not be bundled for the client-side](#write-server-side-code-directly). > Imports used in `getStaticProps` will [not be bundled for the client-side](#write-server-side-code-directly).
...@@ -557,7 +557,7 @@ The `context` parameter is an object containing the following keys: ...@@ -557,7 +557,7 @@ The `context` parameter is an object containing the following keys:
- `props` - A **required** object with the props that will be received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) - `props` - A **required** object with the props that will be received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization)
- `notFound` - An optional boolean value to allow the page to return a 404 status and page. More on [Incremental Static Regeneration](#incremental-static-regeneration) - `notFound` - An optional boolean value to allow the page to return a 404 status and page. More on [Incremental Static Regeneration](#incremental-static-regeneration)
- `redirect` - An optional redirect value to allow redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }` - `redirect` - An optional redirect value to allow redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both.
> **Note**: You can import modules in top-level scope for use in `getServerSideProps`. > **Note**: You can import modules in top-level scope for use in `getServerSideProps`.
> Imports used in `getServerSideProps` will not be bundled for the client-side. > Imports used in `getServerSideProps` will not be bundled for the client-side.
......
...@@ -22,7 +22,7 @@ export type Header = { ...@@ -22,7 +22,7 @@ export type Header = {
headers: Array<{ key: string; value: string }> headers: Array<{ key: string; value: string }>
} }
const allowedStatusCodes = new Set([301, 302, 303, 307, 308]) export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
export function getRedirectStatus(route: Redirect): number { export function getRedirectStatus(route: Redirect): number {
return ( return (
......
...@@ -52,6 +52,7 @@ import { FontManifest, getFontDefinitionFromManifest } from './font-utils' ...@@ -52,6 +52,7 @@ import { FontManifest, getFontDefinitionFromManifest } from './font-utils'
import { LoadComponentsReturnType, ManifestItem } from './load-components' import { LoadComponentsReturnType, ManifestItem } from './load-components'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
import optimizeAmp from './optimize-amp' import optimizeAmp from './optimize-amp'
import { allowedStatusCodes } from '../../lib/load-custom-routes'
function noRouter() { function noRouter() {
const message = const message =
...@@ -307,38 +308,60 @@ const invalidKeysMsg = (methodName: string, invalidKeys: string[]) => { ...@@ -307,38 +308,60 @@ const invalidKeysMsg = (methodName: string, invalidKeys: string[]) => {
type Redirect = { type Redirect = {
permanent: boolean permanent: boolean
destination: string destination: string
statusCode?: number
} }
function checkRedirectValues(redirect: Redirect, req: IncomingMessage) { function checkRedirectValues(
const { destination, permanent } = redirect redirect: Redirect,
let invalidPermanent = typeof permanent !== 'boolean' req: IncomingMessage,
let invalidDestination = typeof destination !== 'string' method: 'getStaticProps' | 'getServerSideProps'
) {
const { destination, permanent, statusCode } = redirect
let errors: string[] = []
const hasStatusCode = typeof statusCode !== 'undefined'
const hasPermanent = typeof permanent !== 'undefined'
if (hasPermanent && hasStatusCode) {
errors.push(`\`permanent\` and \`statusCode\` can not both be provided`)
} else if (hasPermanent && typeof permanent !== 'boolean') {
errors.push(`\`permanent\` must be \`true\` or \`false\``)
} else if (hasStatusCode && !allowedStatusCodes.has(statusCode!)) {
errors.push(
`\`statusCode\` must undefined or one of ${[...allowedStatusCodes].join(
', '
)}`
)
}
const destinationType = typeof destination
if (invalidPermanent || invalidDestination) { if (destinationType !== 'string') {
errors.push(
`\`destination\` should be string but received ${destinationType}`
)
}
if (errors.length > 0) {
throw new Error( throw new Error(
`Invalid redirect object returned from getStaticProps for ${req.url}\n` + `Invalid redirect object returned from ${method} for ${req.url}\n` +
`Expected${ errors.join(' and ') +
invalidPermanent '\n' +
? ` \`permanent\` to be boolean but received ${typeof permanent}`
: ''
}${invalidPermanent && invalidDestination ? ' and' : ''}${
invalidDestination
? ` \`destinatino\` to be string but received ${typeof destination}`
: ''
}\n` +
`See more info here: https://err.sh/vercel/next.js/invalid-redirect-gssp` `See more info here: https://err.sh/vercel/next.js/invalid-redirect-gssp`
) )
} }
} }
function handleRedirect(res: ServerResponse, redirect: Redirect) { function handleRedirect(res: ServerResponse, redirect: Redirect) {
const statusCode = redirect.permanent const statusCode = redirect.statusCode
? redirect.statusCode
: redirect.permanent
? PERMANENT_REDIRECT_STATUS ? PERMANENT_REDIRECT_STATUS
: TEMPORARY_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS
if (redirect.permanent) { if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader('Refresh', `0;url=${redirect.destination}`) res.setHeader('Refresh', `0;url=${redirect.destination}`)
} }
res.statusCode = statusCode res.statusCode = statusCode
res.setHeader('Location', redirect.destination) res.setHeader('Location', redirect.destination)
res.end() res.end()
...@@ -654,7 +677,7 @@ export async function renderToHTML( ...@@ -654,7 +677,7 @@ export async function renderToHTML(
data.redirect && data.redirect &&
typeof data.redirect === 'object' typeof data.redirect === 'object'
) { ) {
checkRedirectValues(data.redirect, req) checkRedirectValues(data.redirect, req, 'getStaticProps')
if (isBuildTimeSSG) { if (isBuildTimeSSG) {
throw new Error( throw new Error(
...@@ -791,7 +814,7 @@ export async function renderToHTML( ...@@ -791,7 +814,7 @@ export async function renderToHTML(
} }
if ('redirect' in data && typeof data.redirect === 'object') { if ('redirect' in data && typeof data.redirect === 'object') {
checkRedirectValues(data.redirect, req) checkRedirectValues(data.redirect, req, 'getServerSideProps')
if (isDataReq) { if (isDataReq) {
;(data as any).props = { ;(data as any).props = {
......
...@@ -25,10 +25,27 @@ export const getStaticProps = ({ params }) => { ...@@ -25,10 +25,27 @@ export const getStaticProps = ({ params }) => {
destination = params.post.split('dest-').pop().replace(/_/g, '/') 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
}
return { return {
redirect: { redirect: {
destination, destination,
permanent: params.post.includes('permanent'), permanent,
statusCode,
}, },
} }
} }
......
...@@ -15,10 +15,27 @@ export const getServerSideProps = ({ params }) => { ...@@ -15,10 +15,27 @@ export const getServerSideProps = ({ params }) => {
destination = params.post.split('dest-').pop().replace(/_/g, '/') 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
}
return { return {
redirect: { redirect: {
destination, destination,
permanent: params.post.includes('permanent'), permanent,
statusCode,
}, },
} }
} }
......
...@@ -55,6 +55,40 @@ const runTests = () => { ...@@ -55,6 +55,40 @@ const runTests = () => {
expect(res.headers.get('refresh')).toMatch(/url=\/404/) expect(res.headers.get('refresh')).toMatch(/url=\/404/)
}) })
it('should apply statusCode 301 redirect when visited directly for GSSP page', async () => {
const res = await fetchViaHTTP(
appPort,
'/gssp-blog/redirect-statusCode-301',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(301)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe('/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,
'/gssp-blog/redirect-statusCode-303',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(303)
const { pathname } = url.parse(res.headers.get('location'))
expect(pathname).toBe('/404')
expect(res.headers.get('refresh')).toBe(null)
})
it('should apply redirect when fallback GSP page is visited directly (internal dynamic)', async () => { it('should apply redirect when fallback GSP page is visited directly (internal dynamic)', async () => {
const browser = await webdriver( const browser = await webdriver(
appPort, appPort,
......
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