> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware/javascript-typescript.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# JavaScript / TypeScript

Register middleware on `defineAgent` or `Workflow` with a `middleware` array. Hook names use **camelCase**.

## Logging middleware

```js
const logging = {
  name: "logging",
  async beforeAgent(ctx) {
    console.log("[agent:start]", ctx.agentName, ctx.input);
  },
  async afterAgent(ctx, result) {
    console.log("[agent:done]", ctx.agentName);
    return result;
  },
  async onAgentError(ctx, err) {
    console.error("[agent:error]", ctx.agentName, err?.message || err);
    throw err;
  },
  async beforeModel(ctx, request) {
    console.log("[model]", { round: request.round, model: request.model });
    return request;
  },
  async beforeTool(ctx, call) {
    console.log("[tool:call]", call.name, call.arguments);
    return call;
  },
  async afterTool(ctx, call, result) {
    console.log("[tool:result]", call.name, result);
    return result;
  },
};

const agent = DNotifier.defineAgent({
  name: "assistant",
  instructions: "Use tools when needed.",
  tools: [searchTool],
  middleware: [logging],
});

await notifier.runAgent(agent, { input: "Find the refund policy" });
```

## Tool access middleware

```js
const allowlist = {
  name: "tool-allowlist",
  async beforeTool(ctx, call) {
    const allowed = ctx.state.allowedTools || [];
    if (!allowed.includes(call.name)) {
      return {
        ...call,
        skip: true,
        result: JSON.stringify({ error: "tool_not_allowed", name: call.name }),
      };
    }
    return call;
  },
};

const agent = DNotifier.defineAgent({
  name: "ops",
  tools: [readMetric, restartService],
  instructions: "Help with ops questions.",
  middleware: [
    {
      async beforeAgent(ctx) {
        ctx.state.allowedTools =
          ctx.state.role === "sre"
            ? ["ops.readMetric", "ops.restartService"]
            : ["ops.readMetric"];
      },
    },
    allowlist,
  ],
});
```

## Workflow access middleware

```js
const access = {
  name: "workflow-access",
  async beforeWorkflow(ctx) {
    const userId = ctx.senderId;
    if (!userId) {
      throw new DNotifier.WorkflowError("Authentication required");
    }
    ctx.state.startedAt = Date.now();
  },
  async afterWorkflow(ctx, result) {
    return { ...result, durationMs: Date.now() - ctx.state.startedAt };
  },
  async onWorkflowComplete(ctx, { status, error }) {
    console.log("[workflow]", status, error?.message);
  },
};

const workflow = new DNotifier.Workflow({
  name: "ops-flow",
  middleware: [access],
  async entry(ctx) {
    return ctx.runAgent("ops");
  },
}).registerAgents({ ops: agent });

await notifier.runWorkflow({
  workflow,
  input: { question: "CPU for api-1?" },
  senderId: "user_123",
});
```

## See also

* [**Middleware overview**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware.md)
* [**Define an agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/define-agent/javascript-typescript.md)
* [**Build a workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/build-workflow/javascript-typescript.md)
