DEV Community

Yashwanth sai Arukuti
Yashwanth sai Arukuti

Posted on

Stop accidentally logging passwords and tokens — fix it in one line

We've all done this.

console.log("User login:", req.body);
// Oops. Password just went to Datadog.

logger.info({ user, token, session });
// Oops. Token just went to Sentry.
Enter fullscreen mode Exit fullscreen mode

I kept doing this in my projects. So I built a tiny npm package
to fix it — fieldmasker.

What it does

It masks sensitive fields from any JavaScript object before it
touches your logger, analytics, or API response.

const fieldmasker = require('fieldmasker');

const user = {
  name: "John",
  email: "john@example.com",
  password: "supersecret",
  token: "sk-abc123xyz",
  card: "4111111111111234"
};

console.log(fieldmasker(user).auto().value());
// {
//   name: "John",
//   email: "john@example.com",
//   password: "****",
//   token: "****",
//   card: "****"
// }
Enter fullscreen mode Exit fullscreen mode

One line. Done.

Install

npm install fieldmasker
Enter fullscreen mode Exit fullscreen mode

Real world usage

Safe Express logging middleware

app.use((req, res, next) => {
  logger.info({
    method: req.method,
    path: req.path,
    body: fieldmasker.auto(req.body) // never log raw body again
  });
  next();
});
Enter fullscreen mode Exit fullscreen mode

Safe Sentry reporting

Sentry.configureScope(scope => {
  scope.setUser(fieldmasker.auto(user));
});
Enter fullscreen mode Exit fullscreen mode

Features

  • Auto-detects 50+ sensitive field names (password, token, apiKey, ssn, card, cvv and more)
  • Works on deeply nested objects and arrays
  • Chainable API
  • Show last N characters: showLast(4)****1234
  • Custom mask string: .mask('[REDACTED]')
  • Zero dependencies
  • TypeScript support

The chainable API

fieldmasker(obj)
  .auto()              // auto-detect sensitive keys
  .add(['employeeId']) // add your own keys
  .skip(['token_count']) // skip false positives
  .showLast(4)         // show last 4 chars
  .mask('[REDACTED]')  // custom mask string
  .value()             // get the result
Enter fullscreen mode Exit fullscreen mode

Why I built it

I'm a fresher just getting into open source. I kept writing
the same utility function in every project to scrub sensitive
data before logging. I figured other developers must be doing
the same thing — so I packaged it up properly with TypeScript
types, 22 tests, and published it.

It already has 200+ downloads in its first week which tells
me I'm not alone!

Would love your feedback — what fields should I add to the
auto-detect list? Any features you'd want?

GitHub: https://github.com/arukutiyash/fieldmask
npm: https://www.npmjs.com/package/fieldmasker

Top comments (0)