I’ve been attempting to setup Geographic redirection for some sites, but havn’t been able to workout exactly what I need.
Its working in some areas, but need some tips on the following:
-
- I see the workers can be scripted into Cloudflare via the website and also setup via a project using Wrangler etc. I’m not certain which method is most appropriate for me.
.
- I see the workers can be scripted into Cloudflare via the website and also setup via a project using Wrangler etc. I’m not certain which method is most appropriate for me.
-
-
Cookie parsing, attempting to parse the cookies doesn’t work,
import { parse } from "cookie"
presents an error, “Uncaught SyntaxError: Cannot use import statement outside a module at line 1 (Code: 10021)”
Is it possible to load this via the website script editor? if so how is that done.
This for example doesn’t work
const cookie = parse(request.headers.get(COOKIE_NAME) || null)
.
-
Cookie parsing, attempting to parse the cookies doesn’t work,
-
- Continue bypassing modification - If the conditions aren’t met, I simply want the request to pass through and do what it was doing, no redirection. How is this done?
var url = new URL(request.url);
return await fetch(url);
Script so far
// import { parse } from "cookie"
const COOKIE_NAME = "__jbcloc"
async function redirectToLocation(location, statusCode, cookieValue){
return new Response(null, {
status: statusCode,
headers: {
'Location': location, // Needs the Location.
'Set-Cookie': COOKIE_NAME + '=' + cookieValue
}
});
}
async function handleRequest(request) {
try{
// Check if the Cookie Exists.
// const cookie = parse(request.headers.get(COOKIE_NAME) || null)
const cookie = null; //request.headers.get(COOKIE_NAME);
const location = (request.cf ? request.cf.country : "");
var url = new URL(request.url);
if (cookie != null) {
// Continue to requested Page..
return await fetch("https://www.example.com.au");
}else{
// If not Check the Location of the User
if(location == "AU"){
// Allgood do nothing.
}else if(location == "NZ"){
// Redirect to .co.nz
return await redirectToLocation('https://www.example.co.nz/', 307, location);
}else{
// Redirect to .com
return await redirectToLocation('https://www.example.com/', 307, location);
}
}
}catch(ex){
// SHOULD Continue to requested Page.. NEVER FAIL!
// Could write to header or similar.
return new Response("ERROR: " + ex.message, {
headers: {
"content-type": "text/html;charset=UTF-8",
},});
}
}
addEventListener("fetch", async event => {
event.respondWith(handleRequest(event.request))
})
Thank you for any assistance.