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
JavaScriptlangchainindexpiiMiddleware
Functionā—Since v1.1

piiMiddleware

Creates a middleware that detects and handles personally identifiable information (PII) in conversations.

This middleware detects common PII types and applies configurable strategies to handle them. It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input and agent output.

Built-in PII types:

  • email: Email addresses
  • credit_card: Credit card numbers (validated with Luhn algorithm)
  • ip: IP addresses (validated)
  • mac_address: MAC addresses
  • url: URLs (both http/https and bare URLs)

Strategies:

  • block: Raise an exception when PII is detected
  • redact: Replace PII with [REDACTED_TYPE] placeholders
  • mask: Partially mask PII (e.g., ****-****-****-1234 for credit card)
  • hash: Replace PII with deterministic hash (e.g., <email_hash:a1b2c3d4>)

Strategy Selection Guide:

Strategy Preserves Identity? Best For
block N/A Avoid PII completely
redact No General compliance, log sanitization
mask No Human readability, customer service UIs
hash Yes (pseudonymous) Analytics, debugging
Copy
piiMiddleware(
  piiType: string,
  options: __type = {}
): AgentMiddleware<StateDefinitionInit | undefined>

Used in Docs

  • Prebuilt middleware

Parameters

NameTypeDescription
piiType*string

Type of PII to detect. Can be a built-in type (email, credit_card, ip, mac_address, url) or a custom type name.

options__type
Default:{}

Configuration options

Example 1

Copy
import { piiMiddleware } from "langchain";
import { createAgent } from "langchain";

// Redact all emails in user input
const agent = createAgent({
  model: "openai:gpt-4",
  middleware: [
    piiMiddleware("email", { strategy: "redact" }),
  ],
});

Example 2

Copy
const agent = createAgent({
  model: "openai:gpt-4o",
  middleware: [
    piiMiddleware("credit_card", { strategy: "mask" }),
    piiMiddleware("url", { strategy: "redact" }),
    piiMiddleware("ip", { strategy: "hash" }),
  ],
});

Example 3

Copy
const agent = createAgent({
  model: "openai:gpt-4",
  middleware: [
    piiMiddleware("api_key", {
      detector: "sk-[a-zA-Z0-9]{32}",
      strategy: "block",
    }),
  ],
});
View source on GitHub