From 7b8d57525a42e50a758c4b74a4f583456e54449e Mon Sep 17 00:00:00 2001 From: Warren R Bank Date: Tue, 21 Dec 2021 16:15:29 -0800 Subject: [PATCH] add ability for redirects to preserve the querystring and hash 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 https://github.com/vercel/serve-handler/pull/154 * upstream PR 144 https://github.com/vercel/serve-handler/pull/144 --- lib/serve-handler/src/index.js | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/lib/serve-handler/src/index.js b/lib/serve-handler/src/index.js index 4e1ce64..9d48854 100644 --- a/lib/serve-handler/src/index.js +++ b/lib/serve-handler/src/index.js @@ -139,7 +139,9 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) } return { target: ensureSlashStart(decodedPath), - statusCode: defaultType + statusCode: defaultType, + preserveQuery: true, + preserveHash: true } } @@ -164,7 +166,9 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) if (target) { return { target: ensureSlashStart(target), - statusCode: defaultType + statusCode: defaultType, + preserveQuery: true, + preserveHash: true } } } @@ -172,13 +176,15 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) // 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 } } } @@ -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()