Search code examples
cloudflare-workers

Cloudflare Workers with almost same routes


I have two routes, track and album

Album

https: //mydomain.com/albums/album/ckzz0lo31882850tnsk1qv9awq

Track

https: //mydomain.com/albums/album/cl018v3uh930220tns5ny4ckde/track/cl0191x11930980tnsx045futm
  1. I create a worker for tack, track_worker and create the routes for track_worker. Route name mydomain.com/albums/album/* It is working as expected.

  2. I create a worker for album, album_worker and create the routes for album_worker. Route name mydomain.com/albums/* It is not working.All the route are pointing to track_wroker.

I think that worker service treated it as same route.

May I know how to create a route in CloudFlare rote for above two url?


Solution

  • check for request url

    addEventListener('fetch', event => {
        event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
        const url = new URL(request.url)
        // detect track
        if (/album\/.*?\/track/.test(url)) {
            return responseForTrack
        }
        // detect album
        else if (/album/.test(url)) {
            return responseForAlbum
        }
        else{
           ....
        }
    }