LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangChain
  • Universal
  • Hub
  • Node
  • Load
  • Serializable
  • Encoder Backed
  • File System
  • In Memory
LangChain Core
  • Agents
  • Caches
  • Base
  • Dispatch
  • Web
  • Manager
  • Promises
  • Chat History
  • Context
  • Base
  • Langsmith
  • Documents
  • Embeddings
  • Errors
  • Example Selectors
  • Indexing
  • Base
  • Chat Models
  • Llms
  • Profile
  • Load
  • Serializable
  • Memory
  • Messages
  • Tool
  • Output Parsers
  • Openai Functions
  • Openai Tools
  • Outputs
  • Prompt Values
  • Prompts
  • Retrievers
  • Document Compressors
  • Runnables
  • Graph
  • Singletons
  • Stores
  • Structured Query
  • Tools
  • Base
  • Console
  • Log Stream
  • Run Collector
  • Tracer Langchain
  • Stream
  • Async Caller
  • Chunk Array
  • Context
  • Env
  • Event Source Parse
  • Format
  • Function Calling
  • Hash
  • Json Patch
  • Json Schema
  • Math
  • Ssrf
  • Stream
  • Testing
  • Tiktoken
  • Types
  • Vectorstores
Text Splitters
MCP Adapters
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangChain
UniversalHubNodeLoadSerializableEncoder BackedFile SystemIn Memory
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsLlmsProfileLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingHashJson PatchJson SchemaMathSsrfStreamTestingTiktokenTypesVectorstores
Text Splitters
MCP Adapters
Language
Theme
JavaScriptlangchainindexcreateMiddleware
Functionā—Since v1.1

createMiddleware

Creates a middleware instance with automatic schema inference.

Copy
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>

Used in Docs

  • Agents
  • Build a RAG agent with LangChain
  • Build a SQL assistant with on-demand skills
  • Build customer support with handoffs
  • Custom middleware

Parameters

NameTypeDescription
config*__type

Middleware configuration

Example 1

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

Example 2

Copy
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