How to Use window.crypto in Node.js

By  on  

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!

Recent Features

Incredible Demos

  • By
    Create Twitter-Style Dropdowns Using jQuery

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!