Skip to main content
npayload is launching soon.
npayloadDocs
Framework Quickstarts

Node.js quickstart

Build an Express server that publishes and receives npayload messages

Build an Express server that publishes messages to npayload and receives them via webhooks.

Prerequisites

  • Node.js 18+
  • An npayload account with machine credentials (get them here)

Set up the project

mkdir npayload-express && cd npayload-express
npm init -y
npm install @npayload/node express
npm install -D typescript @types/express @types/node tsx

Create a .env file:

NPAYLOAD_CLIENT_ID=oac_your_client_id
NPAYLOAD_HMAC_SECRET=your_hmac_secret
WEBHOOK_SECRET=your_webhook_secret
PORT=3000

Create the npayload client

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

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

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

Set up channels and subscriptions

// src/setup.ts
import { npayload } from './npayload';

export async function setup() {
  // Create a channel
  await npayload.channels.create({
    name: 'orders',
    description: 'Order lifecycle events',
    privacy: 'standard',
  });

  // Subscribe via webhook
  await npayload.subscriptions.create({
    channel: 'orders',
    name: 'order-processor',
    type: 'webhook',
    endpoint: {
      url: `${process.env.BASE_URL}/webhooks/orders`,
      method: 'POST',
    },
  });

  console.log('Channel and subscription created.');
}

Build the Express server

// src/server.ts
import express from 'express';
import { npayload } from './npayload';
import { setup } from './setup';

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

// Publish endpoint
app.post('/publish', async (req, res) => {
  const message = await npayload.messages.publish({
    channel: 'orders',
    payload: req.body,
  });

  res.json({ messageId: message.gid });
});

// Webhook receiver
app.post('/webhooks/orders', (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' });
  }

  console.log('Received:', req.body.payload);
  res.status(200).json({ received: true });
});

const PORT = process.env.PORT || 3000;

setup()
  .then(() => {
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
  })
  .catch(console.error);

Run it

npx tsx src/server.ts

Test publishing:

curl -X POST http://localhost:3000/publish \
  -H "Content-Type: application/json" \
  -d '{"event": "order.created", "orderId": "ord_123", "total": 59.98}'

Next steps

Was this page helpful?

On this page