How to Use window.crypto in Node.js

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 post How to Use window.crypto in Node.js appeared first on David Walsh Blog.

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!

The post How to Use window.crypto in Node.js appeared first on David Walsh Blog.


Print Share Comment Cite Upload Translate
APA
David Walsh | Sciencx (2024-03-29T10:30:17+00:00) » How to Use window.crypto in Node.js. Retrieved from https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/.
MLA
" » How to Use window.crypto in Node.js." David Walsh | Sciencx - Thursday October 27, 2022, https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/
HARVARD
David Walsh | Sciencx Thursday October 27, 2022 » How to Use window.crypto in Node.js., viewed 2024-03-29T10:30:17+00:00,<https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/>
VANCOUVER
David Walsh | Sciencx - » How to Use window.crypto in Node.js. [Internet]. [Accessed 2024-03-29T10:30:17+00:00]. Available from: https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/
CHICAGO
" » How to Use window.crypto in Node.js." David Walsh | Sciencx - Accessed 2024-03-29T10:30:17+00:00. https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/
IEEE
" » How to Use window.crypto in Node.js." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/. [Accessed: 2024-03-29T10:30:17+00:00]
rf:citation
» How to Use window.crypto in Node.js | David Walsh | Sciencx | https://www.scien.cx/2022/10/27/how-to-use-window-crypto-in-node-js/ | 2024-03-29T10:30:17+00:00
https://github.com/addpipe/simple-recorderjs-demo