Commit 84264f81 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Add required `permanent: boolean` field to redirect (#10044)

* Add permanent field for redirects

* Update printing redirect status code

* Don't add permanent to routes-manifest
Co-authored-by: 's avatarJoe Haddad <timer150@gmail.com>
parent c30e5428
...@@ -10,6 +10,7 @@ import { pathToRegexp } from 'path-to-regexp' ...@@ -10,6 +10,7 @@ import { pathToRegexp } from 'path-to-regexp'
import { promisify } from 'util' import { promisify } from 'util'
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
import checkCustomRoutes, { import checkCustomRoutes, {
getRedirectStatus,
RouteType, RouteType,
Redirect, Redirect,
Rewrite, Rewrite,
...@@ -22,7 +23,6 @@ import { recursiveReadDir } from '../lib/recursive-readdir' ...@@ -22,7 +23,6 @@ import { recursiveReadDir } from '../lib/recursive-readdir'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup' import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
import { import {
BUILD_MANIFEST, BUILD_MANIFEST,
DEFAULT_REDIRECT_STATUS,
EXPORT_DETAIL, EXPORT_DETAIL,
EXPORT_MARKER, EXPORT_MARKER,
PAGES_MANIFEST, PAGES_MANIFEST,
...@@ -246,7 +246,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -246,7 +246,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
...r, ...r,
...(type === 'redirect' ...(type === 'redirect'
? { ? {
statusCode: r.statusCode || DEFAULT_REDIRECT_STATUS, statusCode: getRedirectStatus(r as Redirect),
permanent: undefined,
} }
: {}), : {}),
regex: routeRegex.source, regex: routeRegex.source,
......
...@@ -4,11 +4,14 @@ import textTable from 'next/dist/compiled/text-table' ...@@ -4,11 +4,14 @@ import textTable from 'next/dist/compiled/text-table'
import path from 'path' import path from 'path'
import { isValidElementType } from 'react-is' import { isValidElementType } from 'react-is'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { Redirect, Rewrite } from '../lib/check-custom-routes' import {
Redirect,
Rewrite,
getRedirectStatus,
} from '../lib/check-custom-routes'
import { SPR_GET_INITIAL_PROPS_CONFLICT } from '../lib/constants' import { SPR_GET_INITIAL_PROPS_CONFLICT } from '../lib/constants'
import prettyBytes from '../lib/pretty-bytes' import prettyBytes from '../lib/pretty-bytes'
import { recursiveReadDir } from '../lib/recursive-readdir' import { recursiveReadDir } from '../lib/recursive-readdir'
import { DEFAULT_REDIRECT_STATUS } from '../next-server/lib/constants'
import { getRouteMatcher, getRouteRegex } from '../next-server/lib/router/utils' import { getRouteMatcher, getRouteRegex } from '../next-server/lib/router/utils'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
import { findPageFile } from '../server/lib/find-page-file' import { findPageFile } from '../server/lib/find-page-file'
...@@ -250,10 +253,7 @@ export function printCustomRoutes({ ...@@ -250,10 +253,7 @@ export function printCustomRoutes({
route.source, route.source,
route.destination, route.destination,
...(isRedirects ...(isRedirects
? [ ? [getRedirectStatus(route as Redirect) + '']
((route as Redirect).statusCode ||
DEFAULT_REDIRECT_STATUS) + '',
]
: []), : []),
] ]
}), }),
......
import { match as regexpMatch } from 'path-to-regexp' import { match as regexpMatch } from 'path-to-regexp'
import {
PERMANENT_REDIRECT_STATUS,
TEMPORARY_REDIRECT_STATUS,
} from '../next-server/lib/constants'
export type Rewrite = { export type Rewrite = {
source: string source: string
...@@ -7,6 +11,7 @@ export type Rewrite = { ...@@ -7,6 +11,7 @@ export type Rewrite = {
export type Redirect = Rewrite & { export type Redirect = Rewrite & {
statusCode?: number statusCode?: number
permanent?: boolean
} }
export type Header = { export type Header = {
...@@ -16,6 +21,13 @@ export type Header = { ...@@ -16,6 +21,13 @@ export type Header = {
const allowedStatusCodes = new Set([301, 302, 303, 307, 308]) const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
export function getRedirectStatus(route: Redirect) {
return (
route.statusCode ||
(route.permanent ? PERMANENT_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS)
)
}
function checkRedirect(route: Redirect) { function checkRedirect(route: Redirect) {
const invalidParts: string[] = [] const invalidParts: string[] = []
let hadInvalidStatus: boolean = false let hadInvalidStatus: boolean = false
...@@ -24,6 +36,10 @@ function checkRedirect(route: Redirect) { ...@@ -24,6 +36,10 @@ function checkRedirect(route: Redirect) {
hadInvalidStatus = true hadInvalidStatus = true
invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`) invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`)
} }
if (typeof route.permanent !== 'boolean' && !route.statusCode) {
invalidParts.push(`\`permanent\` is not set to \`true\` or \`false\``)
}
return { return {
invalidParts, invalidParts,
hadInvalidStatus, hadInvalidStatus,
...@@ -72,7 +88,7 @@ export default function checkCustomRoutes( ...@@ -72,7 +88,7 @@ export default function checkCustomRoutes(
allowedKeys = new Set([ allowedKeys = new Set([
'source', 'source',
'destination', 'destination',
...(isRedirect ? ['statusCode'] : []), ...(isRedirect ? ['statusCode', 'permanent'] : []),
]) ])
} else { } else {
allowedKeys = new Set(['source', 'headers']) allowedKeys = new Set(['source', 'headers'])
...@@ -106,7 +122,7 @@ export default function checkCustomRoutes( ...@@ -106,7 +122,7 @@ export default function checkCustomRoutes(
if (type === 'redirect') { if (type === 'redirect') {
const result = checkRedirect(route as Redirect) const result = checkRedirect(route as Redirect)
hadInvalidStatus = result.hadInvalidStatus hadInvalidStatus = hadInvalidStatus || result.hadInvalidStatus
invalidParts.push(...result.invalidParts) invalidParts.push(...result.invalidParts)
} }
......
...@@ -32,4 +32,5 @@ export const IS_BUNDLED_PAGE_REGEX = /^static[/\\][^/\\]+[/\\]pages.*\.js$/ ...@@ -32,4 +32,5 @@ export const IS_BUNDLED_PAGE_REGEX = /^static[/\\][^/\\]+[/\\]pages.*\.js$/
// matches static/<buildid>/pages/:page*.js // matches static/<buildid>/pages/:page*.js
export const ROUTE_NAME_REGEX = /^static[/\\][^/\\]+[/\\]pages[/\\](.*)\.js$/ export const ROUTE_NAME_REGEX = /^static[/\\][^/\\]+[/\\]pages[/\\](.*)\.js$/
export const SERVERLESS_ROUTE_NAME_REGEX = /^pages[/\\](.*)\.js$/ export const SERVERLESS_ROUTE_NAME_REGEX = /^pages[/\\](.*)\.js$/
export const DEFAULT_REDIRECT_STATUS = 307 export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308
...@@ -17,7 +17,6 @@ import { ...@@ -17,7 +17,6 @@ import {
ROUTES_MANIFEST, ROUTES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
DEFAULT_REDIRECT_STATUS,
} from '../lib/constants' } from '../lib/constants'
import { import {
getRouteMatcher, getRouteMatcher,
...@@ -50,6 +49,7 @@ import { ...@@ -50,6 +49,7 @@ import {
Rewrite, Rewrite,
RouteType, RouteType,
Header, Header,
getRedirectStatus,
} from '../../lib/check-custom-routes' } from '../../lib/check-custom-routes'
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
...@@ -493,8 +493,7 @@ export default class Server { ...@@ -493,8 +493,7 @@ export default class Server {
}) })
res.setHeader('Location', updatedDestination) res.setHeader('Location', updatedDestination)
res.statusCode = res.statusCode = getRedirectStatus(route as Redirect)
(route as Redirect).statusCode || DEFAULT_REDIRECT_STATUS
// Since IE11 doesn't support the 308 header add backwards // Since IE11 doesn't support the 308 header add backwards
// compatibility using refresh header // compatibility using refresh header
......
...@@ -77,10 +77,12 @@ module.exports = { ...@@ -77,10 +77,12 @@ module.exports = {
{ {
source: '/hello/:id/another', source: '/hello/:id/another',
destination: '/blog/:id', destination: '/blog/:id',
permanent: false,
}, },
{ {
source: '/redirect1', source: '/redirect1',
destination: '/', destination: '/',
permanent: false,
}, },
{ {
source: '/redirect2', source: '/redirect2',
...@@ -95,7 +97,7 @@ module.exports = { ...@@ -95,7 +97,7 @@ module.exports = {
{ {
source: '/redirect4', source: '/redirect4',
destination: '/', destination: '/',
statusCode: 308, permanent: true,
}, },
{ {
source: '/redir-chain1', source: '/redir-chain1',
...@@ -115,10 +117,12 @@ module.exports = { ...@@ -115,10 +117,12 @@ module.exports = {
{ {
source: '/to-external', source: '/to-external',
destination: 'https://google.com', destination: 'https://google.com',
permanent: false,
}, },
{ {
source: '/query-redirect/:section/:name', source: '/query-redirect/:section/:name',
destination: '/with-params?first=:section&second=:name', destination: '/with-params?first=:section&second=:name',
permanent: false,
}, },
] ]
}, },
......
...@@ -65,7 +65,7 @@ const runTests = (isDev = false) => { ...@@ -65,7 +65,7 @@ const runTests = (isDev = false) => {
expect(res3location).toBe('/') expect(res3location).toBe('/')
}) })
it('should redirect successfully with default statusCode', async () => { it('should redirect successfully with permanent: false', async () => {
const res = await fetchViaHTTP(appPort, '/redirect1', undefined, { const res = await fetchViaHTTP(appPort, '/redirect1', undefined, {
redirect: 'manual', redirect: 'manual',
}) })
......
...@@ -28,11 +28,13 @@ const invalidRedirects = [ ...@@ -28,11 +28,13 @@ const invalidRedirects = [
{ {
// missing destination // missing destination
source: '/hello', source: '/hello',
permanent: false,
}, },
{ {
// invalid source // invalid source
source: 123, source: 123,
destination: '/another', destination: '/another',
permanent: false,
}, },
{ {
// invalid statusCode type // invalid statusCode type
...@@ -46,15 +48,21 @@ const invalidRedirects = [ ...@@ -46,15 +48,21 @@ const invalidRedirects = [
destination: '/another', destination: '/another',
statusCode: 404, statusCode: 404,
}, },
{
// invalid permanent value
source: '/hello',
destination: '/another',
permanent: 'yes',
},
] ]
const invalidRedirectAssertions = (stderr = '') => { const invalidRedirectAssertions = (stderr = '') => {
expect(stderr).toContain( expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello"}` `\`destination\` is missing for route {"source":"/hello","permanent":false}`
) )
expect(stderr).toContain( expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another"}` `\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}`
) )
expect(stderr).toContain( expect(stderr).toContain(
...@@ -65,6 +73,10 @@ const invalidRedirectAssertions = (stderr = '') => { ...@@ -65,6 +73,10 @@ const invalidRedirectAssertions = (stderr = '') => {
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}` `\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}`
) )
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain( expect(stderr).toContain(
'Valid redirect statusCode values are 301, 302, 303, 307, 308' 'Valid redirect statusCode values are 301, 302, 303, 307, 308'
) )
......
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