javascript / expert
Snippet
Sensitive Data Masking with customInspect
By implementing the 'util.inspect.custom' symbol, you can control how an object is represented when using console.log or util.inspect. This is a best practice for security to prevent accidental logging of sensitive data like API keys, tokens, or passwords in production logs.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import util from 'node:util';class UserCredential {constructor(user, token) {this.user = user;this.token = token;}[util.inspect.custom](depth, opts) {return `UserCredential { user: '${this.user}', token: '[MASKED]' }`;}}console.log(new UserCredential('admin', 'secret_123'));
nodejs
Breakdown
1
[util.inspect.custom](depth, opts) {
Defines a custom formatting function that Node.js internals call during inspection.
2
return `... token: '[MASKED]' }`;
Ensures the sensitive token property is never revealed in the output string.