This recipe transforms deprecated crypto.createCredentials usage to the modern tls.createSecureContext API for managing TLS credentials.
What It Does
The codemod transforms:
- Imports from
node:crypto → node:tls
createCredentials function → createSecureContext
- All function calls to use the new API
Usage
npx codemod nodejs/createCredentials-to-createSecureContext
Examples
// Using the deprecated createCredentials from node:crypto
const { createCredentials } = require('node:crypto');
const credentials = createCredentials({
key: privateKey,
cert: certificate,
ca: [caCertificate]
});
// Updated to use createSecureContext from node:tls
const { createSecureContext } = require('node:tls');
const credentials = createSecureContext({
key: privateKey,
cert: certificate,
ca: [caCertificate]
});
import { createCredentials } from 'node:crypto';
const credentials = createCredentials({
key: privateKey,
cert: certificate,
ca: [caCertificate]
});
import { createSecureContext } from 'node:tls';
const credentials = createSecureContext({
key: privateKey,
cert: certificate,
ca: [caCertificate]
});
Options
The createSecureContext function accepts the same options as the deprecated createCredentials:
key - Private key in PEM format
cert - Certificate chain in PEM format
ca - Array of trusted CA certificates
pfx - PFX or PKCS12 encoded private key and certificate chain
passphrase - Passphrase for the private key or pfx
ciphers - Cipher suite specification
honorCipherOrder - Use server’s cipher preferences
secureProtocol - SSL method to use
- And more - see Node.js TLS documentation
Why Migrate?
crypto.createCredentials was deprecated in Node.js v0.11.13 and may be removed in future versions.
Migrating to tls.createSecureContext:
- Uses the correct module (
tls instead of crypto)
- Aligns with Node.js best practices
- Provides better semantic clarity about the function’s purpose
- Ensures compatibility with future Node.js versions
The tls.createSecureContext function is the standard way to create credentials for TLS servers and clients in Node.js.
Common Use Cases
HTTPS Server
import { createSecureContext } from 'node:tls';
import { createServer } from 'node:https';
import { readFileSync } from 'node:fs';
const credentials = createSecureContext({
key: readFileSync('private-key.pem'),
cert: readFileSync('certificate.pem')
});
const server = createServer({ secureContext: credentials }, (req, res) => {
res.writeHead(200);
res.end('Hello secure world!');
});
TLS Socket
import { connect } from 'node:tls';
import { createSecureContext } from 'node:tls';
const context = createSecureContext({
ca: [caCert]
});
const socket = connect({
host: 'example.com',
port: 8000,
secureContext: context
});
Deprecation Reference
This migration addresses DEP0010.