# createMiddleware

> **Function** in `langchain`

📖 [View in docs](https://reference.langchain.com/javascript/langchain/index/createMiddleware)

Creates a middleware instance with automatic schema inference.

## Signature

```javascript
createMiddleware<TSchema extends StateDefinitionInit | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined, TTools extends readonly ClientTool | ServerTool[] = readonly ClientTool | ServerTool[]>(config: __type): AgentMiddleware<TSchema, TContextSchema, NormalizeContextSchema<TContextSchema>, TTools>
```

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `config` | `__type` | Yes | Middleware configuration |

## Returns

`AgentMiddleware<TSchema, TContextSchema, NormalizeContextSchema<TContextSchema>, TTools>`

A middleware instance

## Examples

### Example 1

```ts
const authMiddleware = createMiddleware({
  name: "AuthMiddleware",
  stateSchema: z.object({
    isAuthenticated: z.boolean().default(false),
  }),
  contextSchema: z.object({
    userId: z.string(),
  }),
  beforeModel: async (state, runtime) => {
    if (!state.isAuthenticated) {
      throw new Error("Not authenticated");
    }
  },
});
```

### Example 2

```ts
import { StateSchema, ReducedValue } from "@langchain/langgraph";

const historyMiddleware = createMiddleware({
  name: "HistoryMiddleware",
  stateSchema: new StateSchema({
    count: z.number().default(0),
    history: new ReducedValue(
      z.array(z.string()).default(() => []),
      { inputSchema: z.string(), reducer: (current, next) => [...current, next] }
    ),
  }),
  beforeModel: async (state, runtime) => {
    return { count: state.count + 1 };
  },
});
```

---

[View source on GitHub](https://github.com/langchain-ai/langchainjs/blob/b0175a5d3b68e8fba44a85bc23879bd06def2f52/libs/langchain/src/agents/middleware.ts#L71)