CloudFlare工作人员-检查Cookie、添加标头、设置Cookie

我只想通过CloudFlare workers为第一次访问者动态添加http-Header。例如,这些标题:

Link: </path/to/file.css>; rel=preload; as=style; nopush
Link: </path/to/script.js>; rel=preload; as=script; nopush

因此,我需要在CloudFlare Worker中通过JavaScript实现以下内容:

  1. 检查客户端上是否存在特定Cookie。
  2. 如果Cookie不存在,则添加http-Header,然后设置特定的Cookie。
  3. 如果Cookie确实存在,则不执行任何操作。

您可以使用代码here。

以下是CF博客中的一个通用示例(涉及Cookie和Header):

// A Service Worker which skips cache if the request contains
// a cookie.
addEventListener('fetch', event => {
  let request = event.request
  if (request.headers.has('Cookie')) {
    // Cookie present. Add Cache-Control: no-cache.
    let newHeaders = new Headers(request.headers)
    newHeaders.set('Cache-Control', 'no-cache')
    event.respondWith(fetch(request, {headers: newHeaders}))
  }

  // Use default behavior.
  return
})

解决方案

以下是一个Cloudflare工作器,它实现了您所描述的内容:

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

async function handle(request) {
  // Check for cookie.
  let cookies = request.headers.get('Cookie') || ""
  if (cookies.includes("returning=true")) {
    // User has been here before. Just pass request through.
    return fetch(request)
  }

  // Forward request to origin, get response.
  let response = await fetch(request)

  // Copy Response object so that we can edit headers.
  response = new Response(response.body, response)

  // Add headers.
  response.headers.append("Link",
      "</path/to/file.css>; rel=preload; as=style; nopush")
  response.headers.append("Link",
      "</path/to/script.js>; rel=preload; as=script; nopush")

  // Set cookie so that we don't add the headers
  // next time.
  response.headers.set("Set-Cookie", "returning=true")

  // Return on to client.
  return response
}

相关文章