Maintenance template made by Workers. Is it possible?

Hi everybody,

I only have a quick and simple question.

I wrote a script on Workers, which shows up a maintenance mode page. Now, the problem is that I applied it to all of my pages on my domain (and subdomains), because if my server goes down, it would be the best, that all of the pages will return the maintenance page. But the problem with this is that if I apply the Worker on the whole of my domain, it will immediately changes everything to the maintenance page, even if my server isn’t down. After I disconnect the route from my Worker, everything stands back, as it was before.

So, my question is that is there an opportunity, to activate/deactivate the route to/from my Worker ONLY if my server goes down OR may be there a remote script (curl, and API, you know…) which I could use to toggle the binding? By the way, the best thing would be if the system would detect the server’s outages and automatically bind the route to my worker and detach them when my server is on again.

Is it possible at all only with Workers? Or this might be accomplished via ‘Custom Pages’ on a higher Plan? What do you think?

Thank you if you can contribute with any ideas!! Laszlo

It should be possible with just the worker.

async function handleRequest(event) {
	
	const {request} = event;

	const response = await fetch(request);
	
	//Server Errors from 500 to 599
	if(response.status >= 500 && response.status <= 599)
	{
		return new Response('Maintenance Page');
	}
	
	//Default response if no Server Errors
	return response;
}
1 Like

Thank you very much!

I would like to insert my own maintenance page, so where should I put it? So I want not just a blank white page with 2 words “Maintenance Page”, but also a complete and unique page with some text and maybe image. Where should I insert the concrete code?
But unfortunately it wasn’t work, I copied your code as is, and always got 1011 error :frowning: .

You are probably missing the addEventListener. Replace htmlTemplate with your template.

addEventListener('fetch', event => {
    event.respondWith(handleRequest(event))
})

const htmlTemplate = `<!doctype html>
<html lang="en">
	<head>
		<title>Maintenance Mode</title>
		<meta charset="UTF-8">
	</head>
	<body><h1>Maintenance Mode</h1></body>
</html>`

const handleRequest = async (event) => {
	
	const {request} = event

	const response = await fetch(request)
	
	//Server Errors from 500 to 599
	if(response.status >= 500 && response.status <= 599)
	{
		return new Response(htmlTemplate, {
			status: 503,
			headers: {
				'content-type': 'text/html;charset=UTF-8'
			}
		})
	}
	
	//Default response if no Server Errors
	return response
}

1 Like

That’s it! Thank you very much, it’s working! :slight_smile:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.