Override response status code from 404 to 200 for S3 SPA


#1

Hi there

I’m trying to figure out how can I override response status code

In my case I have single page application hosted on Amazon S3 which gives me 404 with contents from index.html. In CloudFront there is special settings for this scenario, in CloudFlare it seems that workers can be used to achieve same result

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

async function fetchAndLog(req) {
  const res = await fetch(req)
  console.log('req', res.status, req.url)
  if (res.status === 404 && req.method === 'GET') {
    console.log('overwrite status', req.url)
    res.status = 200
    res.statusText = 'OK'
  }
  return res
}

But it seems like it does not work, I also were trying to create new instance of response but then something broken and browser does not recognize content type.

Wondering if someone can share their snippets for such things


#2

Try creating a new response and copying everything over while changing status and text… You shouldn’t be able to modify the response, which is the behaviour you are seeing.


#3

I did try this as well with no luck unfortunately

Here is code I ended up with:

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

async function fetchAndLog(req) {
    const res = await fetch(req)
    console.log('req', res.status, req.url)

    if (res.status === 404 && req.method === 'GET') {
        console.log('overwrite status', req.url)
        return new Response(res.body, {
            headers: res.headers,
            status: 200
        })
    }
    return res
}

But still see 404


#4

Hm, and one more thing I have noticed:

I am testing is everything ok with:

curl -s -I https://m-employer.rabota.ua/keywords | grep HTTP

Just noticed that browser do show me 200 OK, but curl does 404

Seems like cloudflare workers not going to work for this issue


#5

Sorry for misunderstending, the problem was in curl, when we use it with “-I” flag it sends HEAD requests, and in code I did override status only for GET requests, after small fix I do receive 200 OK everywhere


#6

Glad it worked!