How to Use window.crypto in Node.js

C

codeguru

Member
Freecoin
282
I’ve been writing a bunch of jest tests recently for libraries that use the underlying window.crypto methods like getRandomValues() and window.crypto.subtle key management methods. One problem I run into is that the window.crypto object isn’t available, so I need to shim it.

To use the window.crypto methods, you will need Node 15+. You can set the window.crypto by importing the crypto package and setting it on the global:


const crypto = require('crypto').webcrypto;

// Shims the crypto property onto global
global.crypto = crypto;


I really loathe creating mock functions for missing libraries in Node because they can lead to faulty positives on tests; I really appreciate webcrypto being available!
 

Richest Freecoded User

Most Freecoin

freecoded
freecoded
5,296 Freecoin
P
Peterparker87
1,849 Freecoin
G
GwenJasmine
1,672 Freecoin
J
Johnhendrick
1,551 Freecoin
S
speechhub
898 Freecoin
M
mahlibeardman
793 Freecoin
peterkester96
peterkester96
778 Freecoin
S
Smith16
738 Freecoin
A
Alfrenoe87
618 Freecoin
Davy200
Davy200
590 Freecoin
Top