[Vuejs]-Serve non-generated files on static site

0đź‘Ť

It sounds like there are parts of your site that are not totally static. An “htaccess” file gives directions to Apache web server to handle requests dynamically, but you are not using Apache, you are using Workers. In Workers, we “configure” the web server by writing JavaScript. The good news is that unlike htaccess — which is restricted to a narrow feature set — in JavaScript, you can do just about anything!

When you generated your Workers Sites project with wrangler generate, it created a file called workers-site/index.js. This file was copied from a template, but you are free to edit it to add dynamic features to your site.

It sounds like what you want to do is make sure /my-account/orders/* always serves the same HTML file. Let’s program that in JavaScript.

In your index.js, you’ll see a comment like this:

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

This handlePrefix function is defined at the bottom of the file. It’s actually there as an example. The example code modifies path names by stripping off a prefix.

You want to do something similar but not quite the same: You want to match paths starting with /my-account/orders/, and then you want to remove the rest. So you could write a function like this:

function stripOrderNumber(prefix) {
  return request => {
    let url = new URL(request.url)
    if (url.pathname.startsWith("/my-account/orders/")) {
      // Treat as if the order number weren't given.
      url.pathname = "/my-account/orders/"

      // Update the Request object with the modified URL.
      request = new Request(url, request)
    }

    // Invoke default handling from here.
    // (`mapRequestToAsset` is imported from '@cloudflare/kv-asset-handler'
    // at the top of this file.)
    return mapRequestToAsset(request)
  }
}

Now go back up to the commented line and change it to:

  /**
   * You can add custom logic to how we fetch your assets
   * by configuring the function `mapRequestToAsset`
   */
  options.mapRequestToAsset = stripOrderNumber

Deploy your updated worker, and now /my-account/orders/* should be mapped to /my-account/orders/index.html!

Leave a comment