Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloudflare Workers - SPA with Vuejs

Hello I have deployed my Vue.js app to Cloudflare workers using the following commands:

wrangler generate --site
wrangler publish --env dev

This is my wrangler.toml:

account_id = "xxx"
name = "name"
type = "webpack"
workers_dev = true

[site]
bucket = "./dist"
entry-point = "workers-site"

[env.dev]
name = "name"
route = "xxx.com/*"
zone_id = "XXX"
account_id = "XXX"

The website is fine and live on "xxx.com" but when I refresh the page on any other route I get this error message:

could not find es-es/index.html in your content namespace

Or for example:

could not find category/65/index.html in your content namespace

On nginx I had to create a .htaccess, but I have no idea on how to make it work here.

This is my index.js in case it helps:

import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'

/**
 * The DEBUG flag will do two things that help during development:
 * 1. we will skip caching on the edge, which makes it easier to
 *    debug.
 * 2. we will return an error message on exception in your Response rather
 *    than the default 404.html page.
 */
const DEBUG = false

addEventListener('fetch', event => {
  try {
    event.respondWith(handleEvent(event))
  } catch (e) {
    if (DEBUG) {
      return event.respondWith(
        new Response(e.message || e.toString(), {
          status: 500,
        }),
      )
    }
    event.respondWith(new Response('Internal Error', { status: 500 }))
  }
})

async function handleEvent(event) {
  const url = new URL(event.request.url)
  let options = {}

  /**
   * You can add custom logic to how we fetch your assets
   * by configuring the function `mapRequestToAsset`
   */
  // options.mapRequestToAsset = handlePrefix(/^\/docs/)

  try {
    if (DEBUG) {
      // customize caching
      options.cacheControl = {
        bypassCache: true,
      }
    }
    return await getAssetFromKV(event, options)
  } catch (e) {
    // if an error is thrown try to serve the asset at 404.html
    if (!DEBUG) {
      try {
        let notFoundResponse = await getAssetFromKV(event, {
          mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
        })

        return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
      } catch (e) {}
    }

    return new Response(e.message || e.toString(), { status: 500 })
  }
}

/**
 * Here's one example of how to modify a request to
 * remove a specific prefix, in this case `/docs` from
 * the url. This can be useful if you are deploying to a
 * route on a zone, or if you only want your static content
 * to exist at a specific path.
 */
function handlePrefix(prefix) {
  return request => {
    // compute the default (e.g. / -> index.html)
    let defaultAssetKey = mapRequestToAsset(request)
    let url = new URL(defaultAssetKey.url)

    // strip the prefix from the path for lookup
    url.pathname = url.pathname.replace(prefix, '/')

    // inherit all other props from the default request
    return new Request(url.toString(), defaultAssetKey)
  }
}
like image 257
Marcos Aguayo Avatar asked Oct 17 '19 12:10

Marcos Aguayo


2 Answers

There appears to be a built-way to do this now:

import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler'
...
let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })

https://github.com/cloudflare/kv-asset-handler#servesinglepageapp

like image 133
surj Avatar answered Sep 19 '22 07:09

surj


As you know, Vue.js (like many other SPA frameworks) expects that for any path that doesn't map to a specific file, the server falls back to serving the root /index.html file. Vue will then do routing in browser-side JavaScript. You mentioned that you know how to accomplish this fallback with .htaccess, but how can we do it with Workers?

Good news: In Workers, we can write code to do whatever we want!

In fact, the worker code already has a specific block of code to handle "404 not found" errors. One way to solve the problem would be to change this block of code so that instead of returning the 404 error, it returns /index.html.

The code we want to change is this part:

  } catch (e) {
    // if an error is thrown try to serve the asset at 404.html
    if (!DEBUG) {
      try {
        let notFoundResponse = await getAssetFromKV(event, {
          mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
        })

        return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
      } catch (e) {}
    }

    return new Response(e.message || e.toString(), { status: 500 })
  }

We want to change it to:

  } catch (e) {
    // Fall back to serving `/index.html` on errors.
    return getAssetFromKV(event, {
      mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/index.html`, req),
    })
  }

That should do the trick.


However, the above solution has a slight problem: For any HTML page (other than the root), it will do two lookups, first for the specific path, and only after that will it look for /index.html as a fallback. These lookups are pretty fast, but maybe we can make things faster by being a little bit smarter and detecting HTML pages upfront based on the URL.

To do this, we want to customize the mapRequestToAsset function. You can see a hint about this in a comment in the code:

  /**
   * You can add custom logic to how we fetch your assets
   * by configuring the function `mapRequestToAsset`
   */
  // options.mapRequestToAsset = handlePrefix(/^\/docs/)

Let's go ahead and use it. Replace the above comment with this:

  options.mapRequestToAsset = req => {
    // First let's apply the default handler, which we imported from
    // '@cloudflare/kv-asset-handler' at the top of the file. We do
    // this because the default handler already has logic to detect
    // paths that should map to HTML files, for which it appends
    // `/index.html` to the path.
    req = mapRequestToAsset(req)

    // Now we can detect if the default handler decided to map to
    // index.html in some specific directory.
    if (req.url.endsWith('/index.html')) {
      // Indeed. Let's change it to instead map to the root `/index.html`.
      // This avoids the need to do a redundant lookup that we know will
      // fail.
      return new Request(`${new URL(req.url).origin}/index.html`, req)
    } else {
      // The default handler decided this is not an HTML page. It's probably
      // an image, CSS, or JS file. Leave it as-is.
      return req
    }
  }

Now the code detects specifically HTML requests and replaces them with the root /index.html, so there's no need to waste time looking up a file that doesn't exist only to catch the resulting error. For other kinds of files (images, JS, CSS, etc.) the code will not modify the filename.

like image 24
Kenton Varda Avatar answered Sep 20 '22 07:09

Kenton Varda