How to redirect a SPA using Cloudflare workers?

I have a SPA app that has 3 routes.

  1. / - Home page.
  2. /login - Login page.
  3. /dashboard - Dashboard page.

Deployed this app using Cloudflare pages and this application is publicly available using https://example.com domain name.

Then, I created a Cloudflare worker which will redirect any request that comes to the worker to the SPA application’s Login route - example.com/login.

Cloudflare Workers script:

async function handleRequest(request) {
  return Response.redirect("https://example.com/login", 301)
}

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

Then I added two routes for the worker as example.com and www.example.com .

So now any request that comes to the Cloudflare worker will then redirect to the SPA application login route (example.com/login). The redirect has not happened properly and the SPA application is not rendered.

Can anyone, please let me know what mistake I made in the Cloudflare worker to help me render the SPA app?

You need to check first if the request URL is not /login then only send the 301 redirect.

In this case, no matter which URL they hit (incl. /login), your Workers script will still send a 301 redirect.

Try this:

async function handleRequest(request) {
  const url = new URL(request.url)
  const { pathname } = url
  if (pathname != "/login" && pathname != "/dashboard") {
    return Response.redirect("https://madras.dev/login", 301)
  }
  else {
    return await fetch(request)
  }
}

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
})
1 Like

Thanks a lot. You’re approach works like a charm.

1 Like

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