Skip to content

Guards ​

Guards protect operations before they run. Unlike middleware (which is observational), guards can block operations.

Define a Guard ​

ts
const stopGuard = mesh.guard({ kind: "action", name: /^admin\./ }, ({ state }) => ({
  allow: state.user.role === "admin",
  reason: "Admin access is required."
}));

Guard Targets ​

TargetDescription
{ kind: "action", name: "cart.*" }Guard actions by name
{ kind: "transaction", name: /^checkout/ }Guard transactions
{ kind: "mutation", name: "products.*" }Guard mutations

The name field accepts exact strings, wildcards (*), or RegExp.

Guard Error ​

When a guard blocks an operation, StateMesh throws GuardError:

ts
import { GuardError } from "statemesh-core";

try {
  adminAction();
} catch (error) {
  if (error instanceof GuardError) {
    console.log(error.metadata.reason);  // "Admin access is required."
  }
}

Remove a Guard ​

ts
stopGuard(); // Stop guarding

Important Notes ​

TIP

Guards run before the operation starts. They prevent any state mutation or async work from beginning.

WARNING

Guards are evaluated synchronously. The guard function must return { allow, reason } — not a Promise.

Next Steps ​

Released under the MIT License.