Error("location.href can only be used during request handling ...")

I am trying to import the web-ai package using: import { TextModel } from "@visheratin/web-ai".

When I compile using fastly compute init, I am running into the following issue:

Exception while evaluating JS: (new Error("location.href can only be used during request handling, not during initialization", "<stdin>", 135))
  bin/index.js/<@<stdin>:135:11
  bin/index.js/<@<stdin>:149:11
  bin/index.js@<stdin>:160:9
  __require@<stdin>:10:52
  @<stdin>:163:3
  @<stdin>:164:3

Howdy Anil,

That library has been built for web browsers and does not work in other runtimes such as Fastly Compute@Edge, NodeJS etc. The library uses features such as Web Workers, which are only supported by web browsers.

I’ve written a more involved explanation of the error message you are seeing below:

This particular error is because the library looks to be using a feature in the top-level scope which is not allowed to be used in the top-level scope when running on Fastly Compute@Edge using the @fastly/js-compute runtime.
This is because the top-level scope of the application’ss JavaScript is evaluated during compilation to WebAssembly and so does not have access to the Fastly Compute platform, which the feature this library is using relies upon (location.href). To give a fuller explanation for this exact issue, on Fastly Compute@Edge, the location variable is populated from the incoming request, when compiling the application’s JavaScript and evaluating the top-level script, there is no incoming request and so location can not be populated with anything, which is not what the application author is expecting, so we throw an error instead.

This concept of evaluating the application’s top-level scope is something I believe only our JS runtime does, which is why you may find some npm packages do not work on our runtime.

4 Likes