Skip to main content
npayload is launching soon.
npayloadDocs
SDKs

Node.js SDK

Server-side SDK for publishing messages, managing channels, and verifying webhooks

The @npayload/node SDK provides a full-featured TypeScript client for server-side applications.

Installation

npm install @npayload/node

Authentication

npayload uses OAuth 2.0 with DPoP proof-of-possession. The SDK handles token management automatically.

import { NPayloadAuth, NPayloadClient } from '@npayload/node';

const auth = new NPayloadAuth({
  clientId: process.env.NPAYLOAD_CLIENT_ID!,   // oac_...
  hmacSecret: process.env.NPAYLOAD_HMAC_SECRET!,
});

const npayload = new NPayloadClient({
  auth,
  environment: 'development',
});

Channels

// Create a channel
const channel = await npayload.channels.create({
  name: 'orders',
  description: 'Order lifecycle events',
  privacy: 'standard',  // 'standard' | 'hybrid' | 'e2e'
});

// List channels
const channels = await npayload.channels.list();

// Get a specific channel
const ch = await npayload.channels.get(channel.gid);

Messages

// Publish a single message
const message = await npayload.messages.publish({
  channel: 'orders',
  payload: {
    event: 'order.created',
    orderId: 'ord_12345',
    total: 59.98,
  },
});

// Batch publish
const batch = await npayload.messages.publishBatch({
  channel: 'orders',
  messages: [
    { payload: { event: 'order.created', orderId: 'ord_001' } },
    { payload: { event: 'order.created', orderId: 'ord_002' } },
  ],
});

Subscriptions

// Create a webhook subscription
const subscription = await npayload.subscriptions.create({
  channel: 'orders',
  name: 'fulfillment-service',
  type: 'webhook',
  endpoint: {
    url: 'https://your-service.com/webhooks/orders',
    method: 'POST',
    headers: {
      'Authorization': 'Bearer your-webhook-secret',
    },
  },
  filter: {
    routingKey: 'order.*',
  },
});

// List subscriptions
const subs = await npayload.subscriptions.list({ channel: 'orders' });

Webhook verification

Verify inbound webhook signatures to ensure messages are from npayload:

import express from 'express';

const app = express();
app.use(express.json());

app.post('/webhooks/orders', async (req, res) => {
  const isValid = npayload.webhooks.verify(
    req.body,
    req.headers['x-npayload-signature'] as string,
    process.env.WEBHOOK_SECRET!
  );

  if (!isValid) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  const { payload } = req.body;
  console.log('Received:', payload.event);

  res.status(200).json({ received: true });
});

E2E encryption

For zero-knowledge messaging, use the built-in end-to-end encryption:

import { E2ECrypto } from '@npayload/node';

const crypto = new E2ECrypto();

// Generate key pair (RSA-4096)
const keyPair = await crypto.generateKeyPair();

// Encrypt before publishing
const encrypted = await crypto.encrypt(
  JSON.stringify({ secret: 'data' }),
  recipientPublicKey
);

await npayload.messages.publish({
  channel: 'secure-channel',
  payload: encrypted,
});

Error types

ErrorWhen
AuthenticationErrorInvalid credentials or expired token
ValidationErrorInvalid request parameters
NotFoundErrorResource does not exist
RateLimitErrorRate limit exceeded (includes retryAfter)
SecurityErrorSecurity policy violation
ConflictErrorResource already exists
TimeoutErrorRequest timed out
NPayloadErrorBase error class for all other errors

Next steps

Was this page helpful?

On this page