Skip to content

Commit

Permalink
add ability for redirects to preserve the querystring and hash
Browse files Browse the repository at this point in the history
when the requested URL is redirected, as the result of:
  config.redirects
preserve the querystring and hash, conditional to:
  config.redirects[index].preserveQuery
  config.redirects[index].preserveHash

when the requested URL is redirected, as the result of either:
  config.cleanUrls
  config.trailingSlash
preserve the querystring and hash, without condition

based on:
* upstream PR 154
    vercel/serve-handler#154
* upstream PR 144
    vercel/serve-handler#144
  • Loading branch information
warren-bank committed Dec 22, 2021
1 parent e54b28e commit 7b8d575
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions lib/serve-handler/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl)
}
return {
target: ensureSlashStart(decodedPath),
statusCode: defaultType
statusCode: defaultType,
preserveQuery: true,
preserveHash: true
}
}

Expand All @@ -164,21 +166,25 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl)
if (target) {
return {
target: ensureSlashStart(target),
statusCode: defaultType
statusCode: defaultType,
preserveQuery: true,
preserveHash: true
}
}
}

// This is currently the fastest way to
// iterate over an array
for (let index = 0; index < redirects.length; index++) {
const {source, destination, type} = redirects[index]
const {source, destination, type, preserveQuery, preserveHash} = redirects[index]
const target = toTarget(source, destination, decodedPath)

if (target) {
return {
target,
statusCode: type || defaultType
statusCode: type || defaultType,
preserveQuery: !!preserveQuery,
preserveHash: !!preserveHash
}
}
}
Expand Down Expand Up @@ -763,8 +769,18 @@ module.exports = async (request, response, config = {}, methods = {}) => {
}

if (paths.redirect) {
// conditionally preserve search and hash
let req_url, req_search, req_hash

if (paths.redirect.preserveQuery || paths.redirect.preserveHash) {
req_url = url.parse(request.url)
}

req_search = (paths.redirect.preserveQuery && req_url.search) ? req_url.search : ''
req_hash = (paths.redirect.preserveHash && req_url.hash) ? req_url.hash : ''

response.writeHead(paths.redirect.statusCode, {
Location: encodeURI(paths.redirect.target)
Location: encodeURI(paths.redirect.target + req_search + req_hash)
})

response.end()
Expand Down

0 comments on commit 7b8d575

Please sign in to comment.