How to create multiple pages in one script?

I see that we can create HTML Page using Workers by using https://gist.github.com/ParveenBhadooOfficial/9b0e44d4536dfc05c40ded96a850ae6d
and it https://anyurl.bhadoo.workers.dev/ and https://anyurl.bhadoo.workers.dev/anypath shows same content.

How can we make multiple pages with this on same url with different paths?

I use a simple approach in some cases.

const url = new URL(event.request.url);
let elements = url.pathname.split("/").filter(n => n);

if (elements[0]==='whatever'){
//some html
}

and vary the array position depending on URL level desired.

1 Like

Can you explain it? I tried but it didn’t worked. Please give an example code to work with.

The code is written in this form so that you can understand what is happening, not elegant in anyway.

async function handleRequest(event) {
  const url = new URL(event.request.url);
  let element = url.pathname.split("/").filter(n => n);

  if (element[0] === "whatever") {
    const someHTML = "<html><body>Whatever</body></html>";
    return new Response(someHTML, {
      headers: {
        "content-type": "text/html;charset=UTF-8"
      }
    });
  } else if (element[0] === undefined) {
    const someHTML = "<html><body>Index</body></html>";
    return new Response(someHTML, {
      headers: {
        "content-type": "text/html;charset=UTF-8"
      }
    });
  } else {
    return new Response("Error 404", { status: "404" });
  }
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event));
});

Thank You. It worked. :blush:

I just needed to change “Index” to <html><body>Index</body></html> for multiple lines.