Skip to content

Import the webcrypto API as a single module in both nodejs and browsers.

Notifications You must be signed in to change notification settings

storacha/one-webcrypto

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

one-webcrypto

The WebCrypto API is available in most browsers, under a global variable:

// in web pages
const webcrypto = window.crypto
// in web workers, etc.
const webcrypto = self.crypto
// or generally under
const webcrypto = globalThis.crypto

It is also available in NodeJS since version 15.

However, it is accessed differently:

// in node with commonjs
const webcrypto = require("crypto").webcrypto
// in node with ES Modules
import crypto from "crypto"
const webcrypto = crypto.webcrypto

These different ways of getting access to valuable cryptographic primitives (see webcrypto.subtle) accross platforms (node & browsers) are hard to get right.

Usage

With this package, you can just import the WebCrypto API like so:

import { webcrypto } from "one-webcrypto"

webcrypto.getRandomValues( //...
await webcrypto.subtle.generateKey( //...

Or with CommonJS:

const { webcrypto } = require("one-webcrypto")

Compatibility Issues

This package uses a fairly new package.json standard field, the exports field.

Read more about it:

We're also making use of webpack's pseudo-standard of the "browser" flag for imports.

So if your environment doesn't support that, it may or may not work.

We know that this setup works (should work) with

  • NodeJS 15+ (thus also e.g. mocha)
  • ESBuild
  • Webpack 5
  • Vite
  • SvelteKit
  • Snowpack
  • Parcel 2

We know that this setup can have issues with

  • Create React App

If you have any experience (whether it supports the claims above or not), please create an issue. The idea is to help each other out in these crazy bundler times and document what works and what doesn't. :)

About

Import the webcrypto API as a single module in both nodejs and browsers.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%