Skip to content

Commit

Permalink
feat: ✨ pass on existing search params to redirected url
Browse files Browse the repository at this point in the history
  • Loading branch information
AkashRajpurohit committed Jul 9, 2023
1 parent 678b287 commit 3dc48cf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,20 @@ app.get('/', (c) =>
);

app.get('*', async (c) => {
const incomingUrl = new URL(c.req.url);
const existingSearchParams = incomingUrl.searchParams;

// Get the URL pathname as input text minus the leading "/"
const text = new URL(c.req.url).pathname.slice(1);
const text = incomingUrl.pathname.slice(1);
const { NOT_FOUND_REDIRECT_URL, REFERRER_TEXT } = c.env;
const url = await c.env.GO_URLS.get(text);

if (!url) {
if (NOT_FOUND_REDIRECT_URL) {
const redirectUrl = appendReferrerTextToUrl(
NOT_FOUND_REDIRECT_URL,
REFERRER_TEXT
REFERRER_TEXT,
existingSearchParams
);
return c.redirect(redirectUrl);
}
Expand All @@ -32,7 +36,7 @@ app.get('*', async (c) => {
return c.text('Not found', 404);
}

const urlWithRef = appendReferrerTextToUrl(url, REFERRER_TEXT);
const urlWithRef = appendReferrerTextToUrl(url, REFERRER_TEXT, existingSearchParams);

return c.redirect(urlWithRef, 307);
})
Expand Down
18 changes: 17 additions & 1 deletion src/util.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
export const appendReferrerTextToUrl = (url = '/', referrerText: string) => {
export const appendReferrerTextToUrl = (
url = '/',
referrerText: string,
existingSearchParams: URLSearchParams
) => {
if (!referrerText) return url;

const uri = new URL(url);
uri.searchParams.append('ref', referrerText);

// Append all existing search params to the redirected URL as well
// Note: if existing URL had a ref property then that will override
// the referrerText we set above
for (const [key, value] of existingSearchParams.entries()) {
if (key === 'ref') {
uri.searchParams.delete('ref');
}

uri.searchParams.append(key, value);
}

return uri.toString();
};

0 comments on commit 3dc48cf

Please sign in to comment.