Browse guides

Isolate Valyrian.js execution with scopes

Create one scope, inspect its presence, bind and temporarily replace its value, and keep concurrent server branches separate.

The example confirms an active ServerStorage context, uses hasContext before and inside runWithContext, reads through getContext, restores a temporary setContext value and returns separate results for both branches.

Table of contents

Main APIs

createContextScope
Creates a named context boundary for values that belong to one execution flow.
ContextScope
Type. Typed key for context operations.
getContext
Reads the value associated with a context boundary in the active execution.
hasContext
Reports whether the active execution contains a value for a context boundary.
runWithContext
Runs a synchronous or asynchronous callback with a value bound to a context boundary.
setContext
Supplies a scoped value to later context reads.
isServerContextActive
Reports whether server context storage is active for the current execution.
ServerStorage
Provides request-scoped browser-like storage during server rendering.

Use an execution scope

Run each branch inside ServerStorage, inspect context state, bind its request ID with runWithContext and restore a temporary value written by setContext.

ts
import { ServerStorage } from "valyrian.js/node";
import {
  createContextScope,
  getContext,
  hasContext,
  isServerContextActive,
  runWithContext,
  setContext,
} from "valyrian.js/context";

const requestId = createContextScope<string>("request-id");

async function runRequest(value: string) {
  return ServerStorage.run(() => {
    const active = isServerContextActive();
    const before = hasContext(requestId);
    return runWithContext(requestId, value, async () => {
      const present = hasContext(requestId);
      const current = getContext(requestId);
      const restore = setContext(requestId, value + "-nested");
      const nested = getContext(requestId);
      restore();
      await Promise.resolve();
      const restored = getContext(requestId);
      return { active, before, present, current, nested, restored };
    });
  });
}

const values = await Promise.all([runRequest("alpha"), runRequest("beta")]);
console.log(values);
// true, false, true, alpha, alpha-nested, alpha
// true, false, true, beta, beta-nested, beta

Practice

Result

Both branches report an active server context, no value before binding, the bound and nested values in order, and the original bound value after restore().

Exact references