• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

169
Views
Using subtle in a Javascript module, from both the browser and NodeJS

NodeJS has an experimental implementation of the browser's crypto.subtle.

I have written a Javascript module which runs in both the browser and the NodeJS. It needs access to subtle.

For the moment, every function which needs to use subtle awaits the following function at the beginning of execution:

async function getSubtle() {
  if (typeof window === 'undefined') { // running in NodeJS
    const crypto = await import('crypto');
    return crypto.webcrypto.subtle;
  } else { // running in a browser
    return crypto.subtle;
  }
}

This works, but is slow and ugly as I'm re-importing the code on every function call (in NodeJS).

My project is simple enough that I do not use a build system. (I use express and symlink the modules I require, e.g. from public/js/modules/foo.mjs to lib/foo.js.)

Can I replace getSubtle() with a module-level non-async conditional import? If so, how?

about 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error