Server Setup

A complete walkthrough for setting up a stripe402 server with Express.

Prerequisites

  • Node.js 22+

  • A Stripe account with test API keys

  • Redis running locally (or Docker)

  • Publishable key tokenization enabled in your Stripe dashboard (required for headless clients)

Enable Publishable Key Tokenization

If your API will serve headless clients (AI agents, CLI tools, server-to-server), you must enable direct card tokenization in your Stripe dashboard:

  1. Enable "Publishable key card tokenization"

  2. Save

Stripe shows a warning that this is discouraged for typical web apps — this is expected. stripe402 requires it because programmatic clients cannot interact with Stripe's prebuilt UI elements (Elements, Checkout). This is safe because card details are sent directly to Stripe's servers and the API server only ever sees tokenized pm_... IDs. See the Creating Payment Methods guide for full details.

Note: If your API only serves browser-based clients using Stripe.js Elements, this setting is not required.

Step 1: Install Dependencies

pnpm add @stripe402/express @stripe402/server express stripe ioredis
pnpm add -D typescript @types/express

Step 2: Configure Environment

Create a .env file:

Step 3: Choose a Store

Redis is recommended for most use cases — it's fast, simple, and the Lua script ensures atomic balance operations.

Option B: PostgreSQL

PostgreSQL is better when you need durability guarantees or want to query transaction history with SQL.

Step 4: Configure Routes

Define which routes require payment. The key format is "METHOD /path":

Route Configuration Options

Option
Type
Default
Description

amount

number

(required)

Price per request in units.

currency

string

'usd'

ISO 4217 currency code.

minTopUp

number

50000

Minimum charge per top-up in units.

description

string

Shown in 402 responses and Stripe charge descriptions.

Step 5: Apply Middleware

The middleware runs before your route handlers. It intercepts requests to paid routes and either challenges with 402, deducts credits, or processes payment — then calls next() to let your handler run.

Step 6: Add Route Handlers

Step 7: Test

Complete Example

See the full working example in apps/example/src/server.tsarrow-up-right.

Last updated