I’m trying to use Cloudflare worker to serve a website from my own domain, by following an article I found online.
The website is hosted by a 3rd party service, that I do not own. The article unfortunately is outdated with how Cloudflare looks and works, and I’m having issues.
Article: https://dev.to/just_moh_it/how-to-serve-any-website-from-your-own-domain-for-free-44l9
I’ve followed the steps the best I could.
- Purchase domain through Cloudflare
- Create worker using my domain
- Create Worker Application
- Add custom domain
- Add worker to domain routes
- Add the supplied code (with url inserted)
The only step I did not follow from the article was adding DNS records, as you cannot add them for the domain when using worker proxied.
Any help would be appreciated.
FYI: I am not a developer.
Hi There
From what I understand, you want to return the content (body) of another page
Cloudflare allows you to test your code from their Playground:
https://developers.cloudflare.com/workers/playground/
But I think what you want is this:
/**
* @typedef {Object} Env
*/
export default {
/**
* @param {Request} request
* @param {Env} env
* @param {ExecutionContext} ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
//return fetch("https://workers.cloudflare.com/");
try {
//Add the page to fetch
const response = await fetch("https://workers.cloudflare.com/");
if (response.status == 200 && response.body != null) {
// Handle successful response here
return new Response(response.body);
}
else {
//See Logs in case there is no body in response
console.log(response.body);
return new Response("Response: " + response.statusText);
}
} catch (error) {
// Handle errors
console.log(error);
return new Response("Response: " + error);
}
}
};
Output: