Skip to main content

Overview

QuickJS uses a two-level architecture to manage JavaScript execution environments:
  • JSRuntime - Represents an isolated JavaScript runtime with its own object heap
  • JSContext - Represents a JavaScript realm with its own global objects

JSRuntime

JSRuntime represents a JavaScript runtime corresponding to an object heap. Several runtimes can exist at the same time but they cannot exchange objects. Inside a given runtime, no multi-threading is supported.

Creating a runtime

Runtime isolation

Each runtime maintains its own:
  • Object heap - All JavaScript objects are allocated within a runtime’s heap
  • Garbage collector - Each runtime has independent GC
  • Memory limits - Memory constraints are per-runtime
  • Class definitions - JS classes are registered per-runtime
Objects from different runtimes cannot be mixed. Attempting to use an object from one runtime in another will lead to undefined behavior.

Custom allocators

You can provide custom memory allocation functions:

JSContext

JSContext represents a JavaScript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects.

Creating a context

Context properties

Each context has:
  • Global object - Independent globalThis object
  • Standard objects - Separate Object, Array, Function, etc.
  • Built-in prototypes - Independent prototype chains
  • Module namespace - Separate module registry

Multiple contexts

Contexts within the same runtime can share objects, similar to frames of the same origin in a web browser:

Context use cases

Multiple contexts are useful for:
  • Sandboxing - Isolate untrusted code with separate globals
  • Testing - Create fresh environments for each test
  • Plugin systems - Give each plugin its own namespace
  • Worker simulation - Simulate web workers with shared data

Runtime vs. Context

Best practices

One runtime per application - For most applications, create a single runtime and multiple contexts as needed.
Cleanup order - Always free contexts before freeing the runtime they belong to.
No multithreading - QuickJS does not support multi-threading within a runtime. Use separate runtimes for concurrent execution.

Example: Multi-context application

See also