ES6 import gotchas

ES6 module imports are instantiated once. Subsequent imports return the already instantiated instance of the module. This also happens across subsequent HTTP requests.

To avoid subtle bugs, ES6 modules need to be idempotent (they need to return the same result for first and subsequent imports).

If you have shared state in an imported module, then you can end up with bugs that only show up on subsequent requests or different paths.

Config modules in particular need to be factory functions (return a copy) if there is any risk of code trying to modify the original module object.

Never use a config import with useContext()

Because we use edge workers as our server, it is essential to avoid persistent or shared state in our ES6 module context. Depending on demand, a worker may serve 200 requests and then get recycled. In-memory state is not reliable in this environment.

Try reloading this page to see the difference between an ES6 "singleton" (with shared state) and a factory import (creates a new object every time).

1. shared/persistent state.

sharedState.count
1

2. "singleton" method that references shared/persistent state.

singletonInstance.count
1

3. "factory method" that returns a fresh copy of state every time.

factoryInstance.count
1