Masking Sensitive Data in Client-Side AI Apps

When building web applications that interact with AI models, the most common security flaw is exposing your API key directly in the browser's source code or network traffic. Unlike server-side environments, browsers execute code on the user's machine, making it easy for anyone to inspect network requests and steal credentials. This is especially critical when you are using a service that requires authentication, as a leaked key can lead to unexpected charges or unauthorized access to your model's capabilities.
A common scenario involves sharing a prototype with a friend or colleague. You might feel too awkward to tell them they are burning through your API key, so you write a tool to limit their quota instead. However, if the key itself is visible in the browser console, they could bypass your limits entirely. This article explores how to mask sensitive data and prevent accidental exposure of keys in client-side applications, ensuring your credentials remain secure even when your app is running in an open environment.
The solution lies in a combination of strict environment variable management, local masking libraries, and careful network request handling. By detecting sensitive data before it leaves the browser and swapping it for a realistic fake, you can send messages to AI endpoints without revealing your actual credentials. This approach works for any OpenAI-compatible API, including services that are not affiliated with OpenAI, and helps you maintain control over your usage and costs.
Frequently asked questions
What is an API key in the context of browser interfaces?
An API key is a unique string of characters used to authenticate requests to an AI model. In browser interfaces, it is often hardcoded or stored in local storage, making it vulnerable to inspection. Protecting it requires masking or proxying requests to prevent exposure.
How does local masking differ from server-side proxying?
Local masking detects sensitive data in the browser and replaces it with a fake value before sending the request, while server-side proxying sends the key to a backend server that handles the actual API call. Masking is faster and reduces server load, but requires careful implementation to avoid leaking the key in network logs.
Which is better: using a browser extension or a npm library?
A browser extension is ideal for global protection across multiple tabs and sites, while a npm library is better for specific applications where you control the codebase. Extensions like Discretion offer zero-network-call detection, whereas libraries like @discretion/core allow for custom integration into your project's logic.
What is the role of checksum validation in masking?
Checksum validation, such as Luhn or mod-97, ensures that the detected sensitive data is real and not just a random string. This reduces false positives and ensures that only actual API keys or PII are masked, maintaining the integrity of the AI response while protecting privacy.
How does masking affect AI model performance?
Masking has negligible impact on model performance because the replacement happens locally before the request is sent. The model receives a fake key, but if the endpoint is designed to ignore it (like free-ai), the response is identical to using the real key, provided the masking logic is accurate.
Can I use masking with free API endpoints?
Yes, even with free endpoints like free-ai, masking is useful for protecting PII or other sensitive data in your prompts. Since free-ai is not affiliated with OpenAI and has no key requirement, masking focuses on content privacy rather than key security, but the techniques remain applicable.
What are the risks of storing keys in local storage?
Storing keys in local storage exposes them to XSS attacks and easy retrieval by any script running on the page. It is safer to use in-memory variables or masking libraries that do not persist the key, or to use a backend proxy to handle authentication away from the browser.
How do I test if my masking is working correctly?
You can test by inspecting network requests in the browser developer tools. Look for the masked value in the request payload instead of the real key. Additionally, check the AI response to ensure it matches what you would get with the real key, confirming the masking did not disrupt the communication.
Step by step
- Install Discretion — Install the @discretion/core npm package or use the browser extension to enable local masking of sensitive data in your AI chat messages.
- Configure Detectors — Configure the 113 detectors to match the types of sensitive data you want to mask, such as API keys, credit card numbers, and ID numbers.
- Wrap Prompts — Create a wrapper function that runs your prompt text through the masking engine before sending it to the AI API.
- Test and Verify — Test your masking logic with various inputs and verify that the masked data is not visible in network requests or console logs.
Understanding the Threat Surface
Browser interfaces are inherently public. When you deploy a web application, the JavaScript code, CSS, and network requests are all visible to anyone who knows how to open the developer tools. This transparency is a double-edged sword: it allows for easy debugging but also makes it trivial for malicious actors or curious friends to extract your API keys. If you are using a service that requires authentication, a leaked key can lead to unauthorized usage, data breaches, or unexpected bills.
The threat is not just about theft; it is also about privacy. Even if you are using a free endpoint like free-ai, you might be sending sensitive personal information (PII) in your prompts. Without masking, this data is sent in plain text to the AI provider. By implementing local masking, you can detect and replace sensitive data before it leaves your browser, ensuring that your conversations remain private and your credentials stay secure.
Why Keys Leak in Browsers
Keys often leak because developers hardcode them into JavaScript files or store them in localStorage for convenience. When the browser loads the page, these values are exposed in the network tab. Any user can copy the key and use it in their own application, bypassing your rate limits or billing.
The Role of Network Inspection
Network inspection tools like Chrome DevTools allow users to view every request made by the browser. If your API key is included in the header or body of a request, it is visible to anyone monitoring the traffic. This is why masking is essential for client-side applications.
Local Masking with Discretion
Discretion is an open-source browser extension and npm library that detects sensitive data in your AI chat messages and swaps it for a realistic fake before sending it to the AI model. It uses 113 detectors with real checksum validation (Luhn, mod-97, Verhoeff, etc.) across 47+ countries' ID formats, ensuring that only actual sensitive data is masked. This approach is zero-network-call and fully local, making it fast and privacy-preserving.
The library is also published as a standalone npm package (@discretion/core) if you want to integrate the detection engine into your own project. This allows you to build custom masking logic tailored to your specific needs, such as masking API keys, credit card numbers, or social security numbers. By using Discretion, you can ensure that sensitive data never leaves your browser in its raw form.
How Discretion Works
Discretion scans the text in your chat messages for patterns that match known sensitive data formats. When a match is found, it replaces the data with a fake value that looks realistic but is not valid. This fake value is then sent to the AI model, which processes it as if it were real, but the original data remains hidden.
Integrating @discretion/core
To use @discretion/core in your project, install it via npm and import the detection functions. You can then call these functions on your prompt text before sending it to the API. This gives you full control over the masking process and allows you to customize the detection rules.

Masking API Keys in Requests
When sending requests to an AI API, the API key is typically included in the Authorization header. To protect this key, you can use a masking library to detect the key in your code and replace it with a fake value before the request is sent. This is particularly useful when you are sharing your code with others or deploying it to a public environment.
For example, if you are using the free-ai endpoint, which does not require an API key, you can still mask any other sensitive data in your prompts. However, if you are using a key-based service, masking the key in the header ensures that even if the network request is intercepted, the key is not exposed. This adds an extra layer of security to your client-side application.
Detecting Keys in Headers
You can write a custom function to scan the Authorization header for patterns that match API keys. If a match is found, replace the key with a fake value. This function can be called before every API request to ensure the key is always masked.
Using Fetch API with Masking
When using the Fetch API, you can intercept the request and modify the headers before sending. This allows you to mask the API key dynamically, ensuring that each request is protected without hardcoding the masking logic in multiple places.
Preventing Accidental Exposure
Accidental exposure often happens when developers log API keys to the console or include them in error messages. To prevent this, you should avoid logging sensitive data and use masking libraries to sanitize logs before they are displayed. This ensures that even if a user inspects the console, they will not see your actual API key.
Another common mistake is storing API keys in environment variables that are exposed to the browser. To avoid this, use a backend proxy to handle authentication. The backend stores the key securely and forwards requests to the AI provider, hiding the key from the browser entirely. This is the most secure approach for production applications.
Sanitizing Console Logs
Create a wrapper around console.log that masks sensitive data before printing. This ensures that any debug information you output does not reveal your API key or other sensitive information. This is a simple but effective way to prevent accidental exposure.
Using Environment Variables Safely
Avoid exposing environment variables directly in the browser. Instead, use a build tool to inject them into your code at compile time, or use a backend proxy to manage them. This prevents users from easily accessing the key through the browser's network tab.

Handling PII in Prompts
Even if you are using a free API like free-ai, you might be sending personally identifiable information (PII) in your prompts. This includes names, addresses, phone numbers, and credit card details. By masking PII before sending the prompt, you protect user privacy and reduce the risk of data breaches.
Discretion's detection engine is designed to handle a wide variety of PII formats, including ID numbers from different countries. By integrating this engine into your application, you can ensure that all sensitive data is masked before it is sent to the AI model. This is especially important for applications that handle user data, such as chatbots or customer support tools.
Identifying PII in Text
Use regular expressions and checksum validation to identify PII in your prompts. Discretion's 113 detectors cover a wide range of formats, ensuring that you catch most types of sensitive data. This reduces the chance of missing important information.
Replacing PII with Fakes
Once PII is detected, replace it with a realistic fake value. For example, replace a credit card number with a fake number that passes the Luhn check. This ensures that the AI model can process the data as if it were real, while the actual data remains hidden.
Testing Your Masking Logic
Testing your masking logic is crucial to ensure that it works correctly. You should test with various types of sensitive data, including API keys, credit card numbers, and ID numbers. Verify that the masked data is not visible in the network requests or console logs.
It is also important to test the AI response to ensure that the masking does not disrupt the conversation. The AI model should be able to process the masked data and provide a relevant response. If the masking is too aggressive, it might confuse the model, so you need to find the right balance between security and usability.
Unit Testing Masking Functions
Write unit tests for your masking functions to ensure they correctly detect and replace sensitive data. Test with edge cases, such as empty strings, invalid formats, and multiple instances of PII in a single prompt.
End-to-End Testing
Perform end-to-end testing by sending masked prompts to the AI API and checking the response. Verify that the response is consistent with what you would get using the real data. This ensures that the masking logic is transparent to the AI model.

Best Practices for Client-Side Security
To maximize security in your client-side applications, follow best practices such as using HTTPS for all network requests, avoiding hardcoding keys, and using masking libraries. Additionally, consider using a backend proxy for sensitive operations to keep keys out of the browser entirely.
Regularly audit your code for potential leaks and update your masking libraries to include new detection rules. By staying proactive, you can ensure that your API keys and sensitive data remain protected against emerging threats.
Using HTTPS Everywhere
Always use HTTPS for network requests to encrypt data in transit. This prevents eavesdropping and ensures that your API keys and PII are protected from man-in-the-middle attacks.
Regular Code Audits
Perform regular code audits to identify potential security vulnerabilities. Look for hardcoded keys, insecure storage, and missing masking logic. Address these issues promptly to maintain a secure application.
Integrating with Free API Endpoints
When using free API endpoints like free-ai, you do not need to worry about API key security, but you still need to protect PII. Discretion's masking engine is perfect for this use case, as it detects and replaces sensitive data without requiring authentication.
You can integrate Discretion into your free API calls by wrapping your prompt text with the masking function before sending it to the API. This ensures that your conversations remain private, even when using a free endpoint. For more information on using free endpoints, see Is There a Free API for Testing Models?.
Wrapping Prompts with Discretion
Create a wrapper function that takes your prompt text, runs it through Discretion's masking engine, and returns the masked text. This function can be called before every API request to ensure consistent masking.
Handling Responses
When receiving responses from the AI model, you may need to unmask the data if the model returns sensitive information. Discretion can help with this by providing the original data alongside the masked version, allowing you to restore the real values in the response.

Test the free keyless API right now on our home page to see how it handles your first request.