npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

secure-json-encoder

v1.0.0

Published

Secure JSON encoding/decoding with private key encryption for Node.js and browser

Readme

Secure JSON Encoder

A secure NPM package for encoding and decoding JSON data with AES-256-GCM encryption using a private key. Perfect for securing data transmission between your Node.js server and React application.

Features

  • 🔐 AES-256-GCM Encryption - Military-grade encryption
  • 🔑 Private Key Authentication - Same key required for encode/decode
  • 🌐 Universal Support - Works in Node.js and browsers (React, Vue, etc.)
  • 🚀 Easy to Use - Simple API with async/await support
  • 📦 Zero Dependencies - Uses native crypto APIs
  • Type Safe - Full error handling

Installation

npm install secure-json-encoder

Quick Start

Node.js Server Example

const SecureJSONEncoder = require('secure-json-encoder');

// Initialize with your private key
const PRIVATE_KEY = 'your-secret-private-key-here';
const encoder = new SecureJSONEncoder(PRIVATE_KEY);

// Encode data
const userData = { id: 123, name: 'John Doe' };
const encoded = encoder.encode(userData);

// Decode data
const decoded = encoder.decode(encoded);
console.log(decoded); // { id: 123, name: 'John Doe' }

React Application Example

import SecureJSONEncoder from 'secure-json-encoder';

// Use the SAME private key as your Node.js server
const PRIVATE_KEY = 'your-secret-private-key-here';
const encoder = new SecureJSONEncoder(PRIVATE_KEY);

// Fetch encrypted data from API and decode
async function fetchUserData() {
  const response = await fetch('https://api.example.com/user');
  const result = await response.json();
  
  // Decode the encrypted data
  const userData = await encoder.decode(result.data);
  console.log(userData);
}

// Encode data before sending to API
async function sendData() {
  const data = { message: 'Hello Server!' };
  const encoded = await encoder.encode(data);
  
  await fetch('https://api.example.com/message', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ data: encoded })
  });
}

Use Cases

1. Server sends encrypted data → React decodes it

Node.js Server:

const SecureJSONEncoder = require('secure-json-encoder');
const encoder = new SecureJSONEncoder('my-secret-key-2024');

app.get('/api/user', (req, res) => {
  const userData = { id: 1, email: '[email protected]' };
  const encoded = encoder.encode(userData);
  
  res.json({ data: encoded });
});

React App:

import SecureJSONEncoder from 'secure-json-encoder';
const encoder = new SecureJSONEncoder('my-secret-key-2024');

const response = await fetch('/api/user');
const { data } = await response.json();
const userData = await encoder.decode(data);

2. React sends encrypted data → Server decodes it

React App:

const formData = { username: 'john', password: 'secret' };
const encoded = await encoder.encode(formData);

await fetch('/api/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ data: encoded })
});

Node.js Server:

app.post('/api/login', (req, res) => {
  const decoded = encoder.decode(req.body.data);
  console.log(decoded); // { username: 'john', password: 'secret' }
  
  // Process login...
});

API Reference

Constructor

new SecureJSONEncoder(privateKey)
  • privateKey (string, required): Your secret key (32+ characters recommended)

Methods

encode(data)string (Node.js) / Promise<string> (Browser)

Encrypts and encodes JSON data.

Parameters:

  • data (Object): JSON-serializable data

Returns:

  • Node.js: Encrypted string (synchronous)
  • Browser: Promise resolving to encrypted string (async)

Example:

// Node.js
const encoded = encoder.encode({ message: 'Hello' });

// Browser/React
const encoded = await encoder.encode({ message: 'Hello' });

decode(encodedData)Object (Node.js) / Promise<Object> (Browser)

Decrypts and decodes encrypted string back to JSON.

Parameters:

  • encodedData (string): Encrypted string from encode()

Returns:

  • Node.js: Decrypted object (synchronous)
  • Browser: Promise resolving to decrypted object (async)

Example:

// Node.js
const decoded = encoder.decode(encodedString);

// Browser/React
const decoded = await encoder.decode(encodedString);

Security Notes

Important Security Practices

  1. Keep Your Private Key Secret

    • Never commit your private key to Git
    • Use environment variables: process.env.PRIVATE_KEY
    • Different keys for development/production
  2. Private Key Requirements

    • Minimum 16 characters (32+ recommended)
    • Use random, complex strings
    • Same key required on both server and client
  3. Transport Security

    • Always use HTTPS in production
    • Encryption adds security but doesn't replace HTTPS

Environment Variables

Node.js (.env file):

PRIVATE_KEY=your-super-secret-key-here-min-32-chars
require('dotenv').config();
const encoder = new SecureJSONEncoder(process.env.PRIVATE_KEY);

React (.env file):

REACT_APP_PRIVATE_KEY=your-super-secret-key-here-min-32-chars
const encoder = new SecureJSONEncoder(process.env.REACT_APP_PRIVATE_KEY);

Complete Example

See the examples/ folder for complete implementations:

  • server.js - Express server with encode/decode endpoints
  • nodejs-usage.js - Basic Node.js usage
  • react-usage.jsx - React component example
  • react-api-helper.js - React API helper functions

Running the Example Server

npm install
npm start

Server runs on http://localhost:3000

Test endpoints:

# Get encrypted data
curl http://localhost:3000/api/data

# Encode data
curl -X POST http://localhost:3000/api/encode \
  -H "Content-Type: application/json" \
  -d '{"name":"John","email":"[email protected]"}'

# Decode data
curl -X POST http://localhost:3000/api/decode \
  -H "Content-Type: application/json" \
  -d '{"encoded":"YOUR_ENCODED_STRING_HERE"}'

How It Works

  1. Encoding Process:

    • JSON data → Stringify → AES-256-GCM encryption → Base64 encoding
  2. Decoding Process:

    • Base64 string → Decryption → JSON parsing → Original data
  3. Encryption Details:

    • Algorithm: AES-256-GCM (Authenticated encryption)
    • Key derivation: SHA-256 hash of private key (Node.js) / PBKDF2 (Browser)
    • Random IV for each encryption
    • Authentication tag for integrity verification

Browser Compatibility

  • ✅ Chrome 37+
  • ✅ Firefox 34+
  • ✅ Safari 11+
  • ✅ Edge 12+
  • ✅ All modern browsers with Web Crypto API support

Error Handling

try {
  const encoded = encoder.encode(data);
  const decoded = encoder.decode(encoded);
} catch (error) {
  console.error('Encryption error:', error.message);
  // Handle: Invalid key, corrupted data, wrong key, etc.
}

Common errors:

  • Private key is required - No key provided to constructor
  • Encoding failed - Invalid data format
  • Decoding failed - Wrong key or corrupted encrypted data

License

ISC

Contributing

Issues and pull requests are welcome!

Support

For issues and questions, please open a GitHub issue.