jws vs jose vs jsonwebtoken vs crypto-js vs node-jose
JWT and Cryptographic Libraries for JavaScript Applications
jwsjosejsonwebtokencrypto-jsnode-joseSimilar Packages:
JWT and Cryptographic Libraries for JavaScript Applications

crypto-js, jose, jsonwebtoken, jws, and node-jose are JavaScript libraries used for cryptographic operations and JSON Web Token (JWT) handling. crypto-js provides general-purpose cryptographic functions like AES, SHA, and HMAC but does not natively support JWT standards. jsonwebtoken is a high-level library focused on creating and verifying JWTs, primarily in Node.js environments. jws implements the lower-level JSON Web Signature (JWS) specification, handling only the signing and verification of tokens without claim validation. jose is a modern, standards-compliant implementation of the full JOSE suite (including JWT, JWS, JWE, and JWK) that works seamlessly in both browser and Node.js environments. node-jose was a previous JOSE implementation for Node.js but has been officially deprecated and should not be used in new projects.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
jws42,454,53472418.8 kB32a month agoMIT
jose31,614,7337,242258 kB0a month agoMIT
jsonwebtoken28,059,48018,14143.4 kB186a month agoMIT
crypto-js11,415,99216,367487 kB2752 years agoMIT
node-jose730,877724353 kB703 years agoApache-2.0

JWT and Crypto Libraries in JavaScript: A Practical Guide for Frontend Developers

When building modern web applications that require authentication, secure data exchange, or cryptographic operations, choosing the right library is critical. The packages crypto-js, jose, jsonwebtoken, jws, and node-jose all operate in this space — but they serve different purposes, target different environments, and follow different standards. Let’s cut through the confusion with a clear, practical comparison.

🔐 Core Purpose and Standards Compliance

crypto-js is a general-purpose cryptographic library. It implements common algorithms like AES, SHA-256, HMAC, and PBKDF2. It does not handle JWTs natively — you’d need to manually encode/decode and sign tokens using its primitives.

// crypto-js: manual JWT-like token creation (not recommended for real JWTs)
import CryptoJS from 'crypto-js';

const header = CryptoJS.enc.Utf8.parse(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
const payload = CryptoJS.enc.Utf8.parse(JSON.stringify({ sub: '123', exp: 1735689600 }));
const encodedHeader = header.toString(CryptoJS.enc.Base64).replace(/=/g, '');
const encodedPayload = payload.toString(CryptoJS.enc.Base64).replace(/=/g, '');
const signature = CryptoJS.HmacSHA256(`${encodedHeader}.${encodedPayload}`, 'secret');
const jwt = `${encodedHeader}.${encodedPayload}.${signature.toString(CryptoJS.enc.Base64)}`;

jsonwebtoken is a high-level, widely used library for creating and verifying JSON Web Tokens (JWTs) using symmetric (HMAC) or asymmetric (RSA) keys. It’s designed primarily for Node.js but can be bundled for frontend use.

// jsonwebtoken: sign and verify a JWT
import jwt from 'jsonwebtoken';

const token = jwt.sign({ sub: '123' }, 'secret', { algorithm: 'HS256' });
const decoded = jwt.verify(token, 'secret');

jws is a lower-level library that implements the JSON Web Signature (JWS) specification — the core signing mechanism behind JWTs. It doesn’t handle claims validation (like expiration) — just signing and verification.

// jws: sign and verify a JWS (raw signature)
import jws from 'jws';

const sig = jws.sign({
  header: { alg: 'HS256' },
  payload: { sub: '123' },
  secret: 'secret'
});
const isValid = jws.verify(sig, 'HS256', 'secret');

jose is a modern, standards-compliant implementation of JOSE (JSON Object Signing and Encryption) specifications, including JWS, JWE, JWT, and JWK. It supports both browser and Node.js, uses Web Crypto APIs when available, and emphasizes security best practices.

// jose: sign and verify a JWT
import { SignJWT, jwtVerify } from 'jose';

const secret = new TextEncoder().encode('secret');
const token = await new SignJWT({ sub: '123' })
  .setProtectedHeader({ alg: 'HS256' })
  .setIssuedAt()
  .setExpirationTime('1h')
  .sign(secret);

const { payload } = await jwtVerify(token, secret);

node-jose was a popular JOSE implementation for Node.js, but it has been officially deprecated as of 2021. Its GitHub repository states: “This library is no longer maintained. Please migrate to jose.” Do not use it in new projects.

⚠️ Deprecation Notice: node-jose is deprecated. Avoid it entirely. Use jose instead.

🌐 Environment Support: Browser vs Node.js

  • crypto-js: Works in both browser and Node.js. Pure JavaScript, no native dependencies.
  • jsonwebtoken: Designed for Node.js but can be bundled for browsers (though not officially optimized for it).
  • jws: Also Node.js–first, but can run in browsers via bundlers.
  • jose: Built for both environments. Uses Web Crypto in browsers and Node.js’s crypto module under the hood. Tree-shakable and modular.
  • node-jose: Node.js only — and deprecated.

If you’re building a frontend-only app (e.g., SPA that validates tokens issued by a backend), jose is the safest, most future-proof choice.

🔑 Key Management and Algorithms

jose stands out for its support of JWK (JSON Web Keys) and modern key formats:

// jose: import a public key from PEM
import { importSPKI } from 'jose';

const publicKey = await importSPKI(pemKey, 'RS256');
const { payload } = await jwtVerify(token, publicKey);

In contrast, jsonwebtoken and jws expect raw strings or buffers for secrets/keys, making key rotation and format handling more manual.

crypto-js only supports symmetric cryptography (no RSA/ECDSA), so it cannot verify standard asymmetric JWTs used in OAuth/OpenID flows.

🛡️ Security and Best Practices

  • jose enforces strict validation by default (e.g., requires explicit algorithm declaration, rejects none alg).
  • jsonwebtoken allows disabling validation (e.g., ignoreExpiration: true), which can lead to insecure usage if misconfigured.
  • jws provides minimal abstraction — you must validate claims yourself.
  • crypto-js gives you full control but no JWT-specific safeguards — easy to implement insecure token schemes.

For production systems, especially those handling user authentication, jose’s opinionated, spec-compliant approach reduces the risk of common JWT pitfalls (like algorithm confusion).

🧩 Real-World Usage Scenarios

Scenario 1: Validating an ID Token from Auth0 in a React App

You receive a JWT from an OAuth provider and need to verify its signature and claims in the browser.

  • Best choice: jose
  • Why? Supports RS256, imports JWKs, validates expiration, and works in browsers.
// Using jose in a React component
import { jwtVerify } from 'jose';

async function verifyToken(token, jwk) {
  const publicKey = await jose.importJWK(jwk, 'RS256');
  return await jwtVerify(token, publicKey, {
    issuer: 'https://your-domain.auth0.com/',
    audience: 'your-audience'
  });
}

Scenario 2: Generating a Session Token in a Next.js API Route

You control both issuance and verification in a Node.js backend.

  • Good choice: jsonwebtoken
  • Why? Simple, battle-tested, and sufficient for symmetric HMAC tokens.
// Next.js API route
import jwt from 'jsonwebtoken';

export default function handler(req, res) {
  const token = jwt.sign({ userId: req.user.id }, process.env.JWT_SECRET, {
    expiresIn: '1h'
  });
  res.json({ token });
}

Scenario 3: Encrypting Sensitive Data in Local Storage

You need to encrypt user data before storing it in the browser.

  • Only viable choice: crypto-js
  • Why? jose supports JWE but is overkill; jsonwebtoken and jws don’t do encryption.
// crypto-js for local encryption
import CryptoJS from 'crypto-js';

const encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret').toString();
const bytes = CryptoJS.AES.decrypt(encrypted, 'secret');
const decrypted = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));

📌 Summary Table

PackageJWT SupportBrowser ReadyAsymmetric CryptoDeprecation StatusBest For
crypto-js❌ (manual)ActiveGeneral crypto (AES, SHA, HMAC)
jose✅ (full)ActiveModern, secure JWT/JWS/JWE in any environment
jsonwebtoken⚠️ (bundled)ActiveNode.js backends with simple token needs
jws✅ (JWS only)⚠️ (bundled)ActiveLow-level JWS operations
node-joseDeprecatedDo not use

💡 Final Recommendation

  • For new frontend projects: Use jose. It’s the only actively maintained, browser-friendly, standards-compliant library that handles JWTs securely and correctly.
  • For legacy Node.js backends: jsonwebtoken is acceptable if you’re already using it, but consider migrating to jose for better security defaults.
  • Avoid node-jose completely — it’s deprecated and unmaintained.
  • Use crypto-js only for non-JWT cryptographic tasks, like encrypting local data.

In short: jose is the future. It’s built for the modern web, respects standards, and keeps you out of trouble.

How to Choose: jws vs jose vs jsonwebtoken vs crypto-js vs node-jose
  • jws:

    Choose jws if you need low-level control over JSON Web Signatures without automatic claim validation (like expiration or issuer checks). It’s suitable for specialized scenarios where you’re implementing custom token logic or integrating with systems that only require raw JWS operations, but you’ll need to handle all validation manually.

  • jose:

    Choose jose if you're building a modern application that requires secure, standards-compliant JWT handling in either the browser or Node.js. It supports the full JOSE suite (JWT, JWS, JWE, JWK), uses platform-native crypto APIs, enforces secure defaults, and is actively maintained. Ideal for validating ID tokens from OAuth providers or implementing secure token-based auth in SPAs.

  • jsonwebtoken:

    Choose jsonwebtoken if you're working in a Node.js backend environment and need a simple, high-level API for issuing and verifying symmetric (HMAC) or asymmetric (RSA) JWTs. It’s widely adopted and sufficient for basic token use cases, but be cautious about its permissive defaults and limited browser optimization.

  • crypto-js:

    Choose crypto-js if you need general-purpose cryptographic utilities like AES encryption, SHA hashing, or HMAC signing in the browser or Node.js, and you are not working with JWTs. It’s useful for encrypting local data or implementing custom security protocols, but avoid it for JWT-related tasks since it lacks built-in support for token standards and validation.

  • node-jose:

    Do not choose node-jose for any new project. It has been officially deprecated since 2021, is no longer maintained, and lacks support for modern security practices. Migrate existing implementations to jose, which is its recommended successor and offers better performance, security, and cross-environment compatibility.

README for jws

node-jws Build Status

An implementation of JSON Web Signatures.

This was developed against draft-ietf-jose-json-web-signature-08 and implements the entire spec except X.509 Certificate Chain signing/verifying (patches welcome).

There are both synchronous (jws.sign, jws.verify) and streaming (jws.createSign, jws.createVerify) APIs.

Install

$ npm install jws

Usage

jws.ALGORITHMS

Array of supported algorithms. The following algorithms are currently supported.

alg Parameter ValueDigital Signature or MAC Algorithm
HS256HMAC using SHA-256 hash algorithm
HS384HMAC using SHA-384 hash algorithm
HS512HMAC using SHA-512 hash algorithm
RS256RSASSA using SHA-256 hash algorithm
RS384RSASSA using SHA-384 hash algorithm
RS512RSASSA using SHA-512 hash algorithm
PS256RSASSA-PSS using SHA-256 hash algorithm
PS384RSASSA-PSS using SHA-384 hash algorithm
PS512RSASSA-PSS using SHA-512 hash algorithm
ES256ECDSA using P-256 curve and SHA-256 hash algorithm
ES384ECDSA using P-384 curve and SHA-384 hash algorithm
ES512ECDSA using P-521 curve and SHA-512 hash algorithm
noneNo digital signature or MAC value included

jws.sign(options)

(Synchronous) Return a JSON Web Signature for a header and a payload.

Options:

  • header
  • payload
  • secret or privateKey
  • encoding (Optional, defaults to 'utf8')

header must be an object with an alg property. header.alg must be one a value found in jws.ALGORITHMS. See above for a table of supported algorithms.

If payload is not a buffer or a string, it will be coerced into a string using JSON.stringify.

Example

const signature = jws.sign({
  header: { alg: 'HS256' },
  payload: 'h. jon benjamin',
  secret: 'has a van',
});

jws.verify(signature, algorithm, secretOrKey)

(Synchronous) Returns true or false for whether a signature matches a secret or key.

signature is a JWS Signature. header.alg must be a value found in jws.ALGORITHMS. See above for a table of supported algorithms. secretOrKey is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.

Note that the "alg" value from the signature header is ignored.

jws.decode(signature)

(Synchronous) Returns the decoded header, decoded payload, and signature parts of the JWS Signature.

Returns an object with three properties, e.g.

{ header: { alg: 'HS256' },
  payload: 'h. jon benjamin',
  signature: 'YOWPewyGHKu4Y_0M_vtlEnNlqmFOclqp4Hy6hVHfFT4'
}

jws.createSign(options)

Returns a new SignStream object.

Options:

  • header (required)
  • payload
  • key || privateKey || secret
  • encoding (Optional, defaults to 'utf8')

Other than header, all options expect a string or a buffer when the value is known ahead of time, or a stream for convenience. key/privateKey/secret may also be an object when using an encrypted private key, see the crypto documentation.

Example:


// This...
jws.createSign({
  header: { alg: 'RS256' },
  privateKey: privateKeyStream,
  payload: payloadStream,
}).on('done', function(signature) {
  // ...
});

// is equivalent to this:
const signer = jws.createSign({
  header: { alg: 'RS256' },
});
privateKeyStream.pipe(signer.privateKey);
payloadStream.pipe(signer.payload);
signer.on('done', function(signature) {
  // ...
});

jws.createVerify(options)

Returns a new VerifyStream object.

Options:

  • signature
  • algorithm
  • key || publicKey || secret
  • encoding (Optional, defaults to 'utf8')

All options expect a string or a buffer when the value is known ahead of time, or a stream for convenience.

Example:


// This...
jws.createVerify({
  publicKey: pubKeyStream,
  signature: sigStream,
}).on('done', function(verified, obj) {
  // ...
});

// is equivilant to this:
const verifier = jws.createVerify();
pubKeyStream.pipe(verifier.publicKey);
sigStream.pipe(verifier.signature);
verifier.on('done', function(verified, obj) {
  // ...
});

Class: SignStream

A Readable Stream that emits a single data event (the calculated signature) when done.

Event: 'done'

function (signature) { }

signer.payload

A Writable Stream that expects the JWS payload. Do not use if you passed a payload option to the constructor.

Example:

payloadStream.pipe(signer.payload);

signer.secret
signer.key
signer.privateKey

A Writable Stream. Expects the JWS secret for HMAC, or the privateKey for ECDSA and RSA. Do not use if you passed a secret or key option to the constructor.

Example:

privateKeyStream.pipe(signer.privateKey);

Class: VerifyStream

This is a Readable Stream that emits a single data event, the result of whether or not that signature was valid.

Event: 'done'

function (valid, obj) { }

valid is a boolean for whether or not the signature is valid.

verifier.signature

A Writable Stream that expects a JWS Signature. Do not use if you passed a signature option to the constructor.

verifier.secret
verifier.key
verifier.publicKey

A Writable Stream that expects a public key or secret. Do not use if you passed a key or secret option to the constructor.

TODO

  • It feels like there should be some convenience options/APIs for defining the algorithm rather than having to define a header object with { alg: 'ES512' } or whatever every time.

  • X.509 support, ugh

License

MIT

Copyright (c) 2013-2015 Brian J. Brennan

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.