Was asked here (Redirect Management with Workers) to post my version of the redirect Worker, which in my case is a sort of shortening service.
Didn’t implement a way to add redirects since it would require a separate database (or the Workers KV product, but since it’s missing a way to see all the contents would make eventual changes to the data hard without having a separate collection of the things added, waiting from updates from @alexcf).
The choice for the analytics tag (which are optional, you could simply not include the part in the data and it will work) is made on the Google Analytics recommendation of using at least the campaign, the medium and the source.
Any suggestion is welcome!
addEventListener('fetch', event => {
event.respondWith(shortURL(event.request))
})
async function shortURL(request) {
let redirects = {
'google': {
'redirect': 'https://www.google.com/',
'utm': {
'campaign': 'cf-community',
'content': '',
'medium': 'web',
'source': 'community',
'term': ''
}
},
'abcdefg': {
'redirect': 'https://www.example.com/',
'utm': {
'campaign': 'cf-community',
'content': 'redirect',
'medium': 'web',
'source': 'community',
'term': 'abcdefg'
}
}
}
let url = new URL(request.url)
let URLpath = url.pathname.substr(4).split('/')
// This assumes a path for the shortening service /go/,
// missing that and using it on the base domain would
// have the number to 1 (to skip the first /)
let redirectObj = redirects[URLpath[0]]
var redirectURL = redirectObj.redirect
if (redirectObj.utm.source && redirectObj.utm.medium && redirectObj.utm.campaign) {
redirectURL += '?utm_source=' + redirectObj.utm.source + '&utm_medium=' + redirectObj.utm.medium + '&utm_campaign=' + redirectObj.utm.campaign
if (redirectObj.utm.term) {
redirectURL += '&utm_term=' + redirectObj.utm.term;
}
if (redirectObj.utm.content) {
redirectURL += '&utm_content=' + redirectObj.utm.content;
}
}
return Response.redirect(redirectURL, 302)
}