Mask PII before calling OpenAI in Node.js and TypeScript
Find names, emails, phone numbers and other personal information in the prompt inside your own Node.js
process, send OpenAI the placeholders, and put the real values back in the answer.
Install
npm install @newmean-ai/pii openai
The package ships its TypeScript types. Apache-2.0.
Mask, call, restore
import OpenAI from "openai";
import { createRedactor, createVault } from "@newmean-ai/pii";
const openai = new OpenAI(); // reads OPENAI_API_KEY
const redactor = await createRedactor(); // medium; create once, reuse
const vault = createVault(); // one per user or conversation
const prompt = "Draft a reply to Kim Minsu (kim@example.com) about the refund.";
const { text } = await redactor.redact(prompt, { vault });
// "Draft a reply to [PERSON_1] ([EMAIL_1]) about the refund."
const response = await openai.responses.create({
model: "gpt-6.1",
instructions: "Copy text in square brackets, such as [PERSON_1], exactly as written.",
input: text,
});
console.log(vault.restore(response.output_text)); // [PERSON_1] → Kim Minsu
Save it as app.ts and run node app.ts (we ran it on Node.js 25.9, which strips
the types), or as app.mjs: the code has no type annotations, so it is plain JavaScript too.
What OpenAI receives
Detection runs in your process. The request body holds the masked text, not the name or the email address:
"input": "Draft a reply to [PERSON_1] ([EMAIL_1]) about the refund."
Captured from the code above, run against a local stand-in for the API (OPENAI_BASE_URL).
Putting the values back
- The vault keeps the map from each numbered placeholder to its value in your process; nothing in it is sent.
Within one vault, a value keeps its placeholder, so a conversation stays the same from turn to turn.
vault.restore() brings back placeholders only as written: [PERSON_1] is restored,
[Person_1] or a translated tag stays as the model wrote it. The instructions line asks the model to copy them.
- For a stream,
vault.restorer() holds back a placeholder split across chunks until it is complete.
- Never share a vault between users: one user's answer could bring back another user's values.
- With the Vercel AI SDK or LangChain.js, the package's middleware masks what the model finds in the messages of the
roles it is set to and, with a vault, restores this call's placeholders in the answer:
how the vault works, and its limits.
Limits
- No detector finds everything: what the model misses is sent as written. Use it to lower what is sent, not as a
guarantee of anonymity (misses by language and label).
- In Node.js the model files are downloaded from Hugging Face each time a redactor is created (there is no Cache API),
so create one per process, or serve the files yourself with
modelUrl.