Isomorphic.js Utilities

0.2.5 · maintenance · verified Sun Apr 19

Isomorphic.js is a utility library providing a consistent API for platform-specific JavaScript features, with a strong focus on cryptographic operations like `randomBytes`, `encrypt`, and `decrypt`. It also offers environment detection utilities such as `isBrowser` and `isNode`. Currently at version `0.2.5`, the package receives infrequent, maintenance-oriented updates, primarily for dependency bumps. Its key differentiator is abstracting away the complexities of disparate browser and Node.js environments, offering polyfills where native APIs are unavailable, thereby enabling truly isomorphic code execution without explicit runtime checks for common tasks, particularly in security-sensitive areas. It relies on `yjs` for some environment detection logic, simplifying cross-platform development.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates environment detection, random byte generation, and basic (though simplified for security) encryption/decryption using the isomorphic API.

import { isBrowser, isNode, randomBytes, encrypt, decrypt } from 'isomorphic.js';

async function runIsomorphicExample() {
  if (isBrowser) {
    console.log('Running in a browser environment.');
  } else if (isNode) {
    console.log('Running in a Node.js environment.');
  } else {
    console.log('Running in an unknown environment.');
  }

  // Generate 16 random bytes
  const randomBuffer = randomBytes(16);
  console.log('Generated random bytes:', randomBuffer.toString('hex'));

  // Example of cryptographic operations (using a dummy key for demonstration)
  const key = await decrypt(Buffer.from('dummy-key-for-test', 'utf-8'), Buffer.from('')); // Key must be derived or generated securely
  const dataToEncrypt = Buffer.from('Hello, Isomorphic World!');
  
  try {
    // Note: `encrypt` and `decrypt` require proper key management and IVs for real-world use.
    // This example is simplified and might not run without a valid crypto key setup.
    const encryptedData = await encrypt(dataToEncrypt, key);
    console.log('Encrypted data (truncated):', encryptedData.toString('hex').substring(0, 30) + '...');

    const decryptedData = await decrypt(encryptedData, key);
    console.log('Decrypted data:', decryptedData.toString());
  } catch (error) {
    console.warn('Could not perform encryption/decryption. Ensure a valid crypto key and IV setup:', error.message);
  }
}

runIsomorphicExample().catch(console.error);

view raw JSON →