JavaScript SDK

Official JavaScript SDK for Node.js and browser environments.

Installation

npm
npm install @truthmark/sdk
yarn
yarn add @truthmark/sdk

Quick Example

const { TruthMarkClient } = require('@truthmark/sdk');

const client = new TruthMarkClient({
  apiKey: 'tm_live_your_key',
  baseUrl: 'https://truthmark-api.onrender.com'
});

// Encode a watermark
const result = await client.encode(
  './photo.jpg',
  'Copyright 2025 - My Company'
);
console.log(`Download: ${result.download_url}`);
console.log(`PSNR: ${result.metadata.psnr} dB`);

// Decode a watermark
const decoded = await client.decode('./watermarked.jpg');
if (decoded.found) {
  console.log(`Message: ${decoded.message}`);
  console.log(`Confidence: ${(decoded.confidence * 100).toFixed(1)}%`);
} else {
  console.log('No watermark found');
}

API Reference

new TruthMarkClient(config?)

Create a new client instance.

Parameters:

  • apiKey (string, optional): Your TruthMark API key
  • baseUrl (string, optional): API base URL. Defaults to production.
const client = new TruthMarkClient({
  apiKey: 'tm_live_your_key',
  baseUrl: 'https://truthmark-api.onrender.com'
});

encode(image, message)

Embed an invisible watermark into an image.

Parameters:

  • image: File path (Node.js) or File/Blob (browser)
  • message: Text to embed (max 500 chars)

Returns:

// Returns Promise<EncodeResult>
{
  status: 'success',
  metadata: { psnr: 42.5, bits_embedded: 256 },
  download_url: 'https://...',
  filename: 'truthmark-protected.png'
}

decode(image)

Extract watermark from an image.

Returns:

// Returns Promise<DecodeResult>
{ found: true, message: 'Extracted text', confidence: 0.95 }

Error Handling

try {
  const result = await client.encode(file, message);
  console.log('Success:', result.download_url);
} catch (error) {
  if (error.status === 401) {
    console.error('Invalid API key');
  } else if (error.status === 429) {
    console.error('Rate limited. Retry after:', error.retryAfter);
  } else {
    console.error('Error:', error.message);
  }
}

Advanced Examples

Next.js API Route

// app/api/watermark/route.ts
import { TruthMarkClient } from '@truthmark/sdk';

const client = new TruthMarkClient({
  apiKey: process.env.TRUTHMARK_API_KEY
});

export async function POST(request) {
  const formData = await request.formData();
  const file = formData.get('file');
  const message = formData.get('message');

  if (!file || !message) {
    return Response.json({ error: 'Missing file or message' }, { status: 400 });
  }

  const result = await client.encode(file, message);
  return Response.json(result);
}

Express.js Middleware

const express = require('express');
const multer = require('multer');
const { TruthMarkClient } = require('@truthmark/sdk');

const app = express();
const upload = multer();
const client = new TruthMarkClient({
  apiKey: process.env.TRUTHMARK_API_KEY
});

app.post('/watermark', upload.single('image'), async (req, res) => {
  try {
    const result = await client.encode(req.file.buffer, req.body.message);
    res.json(result);
  } catch (err) {
    res.status(err.status || 500).json({ error: err.message });
  }
});

app.listen(3000);

Batch Processing

const fs = require('fs');
const path = require('path');

const images = fs.readdirSync('./images')
  .filter(f => /\.(png|jpg|jpeg)$/i.test(f));

const CONCURRENCY = 5;
for (let i = 0; i < images.length; i += CONCURRENCY) {
  const batch = images.slice(i, i + CONCURRENCY);
  const results = await Promise.all(
    batch.map(img =>
      client.encode(
        path.join('./images', img),
        JSON.stringify({ file: img, owner: '© 2025' })
      )
    )
  );
  results.forEach((r, j) =>
    console.log(`✓ ${batch[j]}: PSNR=${r.metadata.psnr.toFixed(1)}dB`)
  );
}

Best Practices

Use environment variables for API keys

Never hardcode keys. Use process.env.TRUTHMARK_API_KEY.

Handle rate limits with retry

Implement exponential backoff when receiving 429 responses.

Don't expose API keys in client-side code

Use server-side API routes to proxy requests from the browser.

Need Help?

Check out the API reference or reach out to support.