How to encrypt data in Node.js
Encrypting sensitive data is crucial for protecting user information, API keys, and confidential data in Node.js applications from unauthorized access.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented data encryption in countless Node.js backend systems and enterprise applications.
From my 25 years of experience in web development and 11 years with Node.js, the most secure and reliable approach is to use the built-in crypto module with AES encryption.
This method provides strong cryptographic protection suitable for production applications.
Use the crypto module with AES-256-GCM encryption for secure data protection with authentication.
const crypto = require('crypto')
function encrypt(text, secretKey) {
const algorithm = 'aes-256-gcm'
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipher(algorithm, secretKey, iv)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
const authTag = cipher.getAuthTag()
return {
encrypted,
iv: iv.toString('hex'),
authTag: authTag.toString('hex')
}
}
// Usage example
const secretKey = crypto.randomBytes(32).toString('hex')
const sensitiveData = 'user credit card: 4111-1111-1111-1111'
const encryptedData = encrypt(sensitiveData, secretKey)
console.log('Encrypted:', encryptedData.encrypted)
console.log('IV:', encryptedData.iv)
console.log('Auth Tag:', encryptedData.authTag)
The crypto.createCipher() method creates an encryption cipher using AES-256-GCM, which provides both encryption and authentication. The initialization vector (IV) ensures that encrypting the same data multiple times produces different results. The getAuthTag() method returns an authentication tag that verifies data integrity during decryption. Store the encrypted data, IV, and authentication tag together - all are needed for successful decryption.
This is the same encryption approach we use in CoreUI backend services for protecting sensitive user data and API credentials. Always use environment variables or secure key management systems to store encryption keys - never hardcode them in your application source code.



