PayWeavePayWeaveBack to Home
Apps

Express Middleware

The @payweave/express package provides route-level middleware for Express applications. Wrap any route with payweave.charge() to require micropayment before your handler executes.

Installation

Terminal
npm install @payweave/express

Basic setup

Create a Payweave instance with your credentials, then use .charge() as standard Express middleware on any route:

TypeScript
import express from 'express';
import { Payweave } from '@payweave/express';

const app = express();
const payweave = new Payweave(
  process.env.PAYWEAVE_APP_ID!,
  process.env.PAYWEAVE_APP_SECRET!
);

app.get(
  '/api/translate',
  payweave.charge({ price: '0.002', description: 'Translation API' }),
  (req, res) => {
    res.json({ translated: 'Hola mundo' });
  }
);

app.listen(3000);

Dynamic pricing

Pass a function to price to compute the cost based on the incoming request. The function receives the Express req object:

TypeScript
app.post(
  '/api/generate',
  payweave.charge({
    price: (req) => req.body.highRes ? '0.05' : '0.005',
    description: 'Image generation',
  }),
  (req, res) => {
    // handler runs only after payment is verified
    res.json({ imageUrl: '...' });
  }
);

Adding metadata

The meta field attaches arbitrary key-value data to the payment record. This is useful for correlating payments with your own analytics:

TypeScript
payweave.charge({
  price: '0.001',
  description: 'Lookup API',
  meta: { tier: 'standard', version: 'v2' },
})

Accessing the payment receipt

After successful payment, the middleware attaches a Payment-Receipt header to the response and adds req.payweave with the receipt details:

TypeScript
app.get(
  '/api/data',
  payweave.charge({ price: '0.001', description: 'Data API' }),
  (req, res) => {
    const { txId, payer } = req.payweave;
    res.json({ data: '...', txId });
  }
);
Express middleware is positional - place payweave.charge() before your handler in the argument list. You can also chain it with other middleware like rate limiters or validators.

Error handling

If payment verification fails, the middleware responds with a 402 status automatically. You can add a custom error handler downstream to log or customize the response:

TypeScript
app.use((err, req, res, next) => {
  if (err.code === 'PAYMENT_FAILED') {
    res.status(402).json({ error: 'Payment required', details: err.message });
  } else {
    next(err);
  }
});