Unverified Commit 463d30ec authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add handling for external redirects (#9764)

parent dbc0853e
......@@ -40,7 +40,7 @@ export default function checkCustomRoutes(
invalidParts.push('`destination` is missing')
} else if (typeof route.destination !== 'string') {
invalidParts.push('`destination` is not a string')
} else if (!route.destination.startsWith('/')) {
} else if (type === 'rewrite' && !route.destination.startsWith('/')) {
invalidParts.push('`destination` does not start with /')
}
......
......@@ -404,7 +404,10 @@ export default class Server {
statusCode: route.statusCode,
name: `${route.type} ${route.source} route`,
fn: async (_req, res, params, _parsedUrl) => {
let destinationCompiler = compilePathToRegex(route.destination)
const parsedDestination = parseUrl(route.destination, true)
let destinationCompiler = compilePathToRegex(
`${parsedDestination.pathname!}${parsedDestination.hash || ''}`
)
let newUrl
try {
......@@ -423,7 +426,15 @@ export default class Server {
}
if (route.type === 'redirect') {
res.setHeader('Location', newUrl)
const parsedNewUrl = parseUrl(newUrl)
res.setHeader(
'Location',
formatUrl({
...parsedDestination,
pathname: parsedNewUrl.pathname,
hash: parsedNewUrl.hash,
})
)
res.statusCode = route.statusCode || DEFAULT_REDIRECT_STATUS
res.end()
return {
......
......@@ -92,6 +92,10 @@ module.exports = {
destination: '/',
statusCode: 303,
},
{
source: '/to-external',
destination: 'https://google.com',
},
]
},
},
......
......@@ -152,6 +152,15 @@ const runTests = (isDev = false) => {
expect(await getBrowserBodyText(browser)).toMatch(/Hello again/)
})
it('should allow redirecting to external resource', async () => {
const res = await fetchViaHTTP(appPort, '/to-external', undefined, {
redirect: 'manual',
})
const location = res.headers.get('location')
expect(res.status).toBe(307)
expect(location).toBe('https://google.com/')
})
if (!isDev) {
it('should output routes-manifest successfully', async () => {
const manifest = await fs.readJSON(
......@@ -237,6 +246,13 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/redir-chain3$'),
regexKeys: [],
},
{
destination: 'https://google.com',
regex: normalizeRegEx('^\\/to-external$'),
regexKeys: [],
source: '/to-external',
statusCode: 307,
},
],
rewrites: [
{
......
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