Skip to content
Engineering

Use Stampwing with Node.js and Next.js

Install an actual SDK artifact and adapt a working Test integration to your own server application.

THE SHORT ANSWER

Use @postrune/sdk in server-side Node.js code. Its exported client is Postrune. Supply the deployment origin and a scoped key, and persist one idempotency key per business event. The package names are compatibility identifiers, not a different product.

Before you start #

For
JavaScript and TypeScript developers using Node.js 22+ or a compatible Next.js App Router application.
Bring
A separate consumer app, the verified SDK download, and the Test credential from the quickstart.
Scope
Registry publication is not assumed. If a verified package download is unavailable, use the dependency-free HTTP sender instead. Next.js snippets show backend integration, not a ready-made public send endpoint.

1. Download the verified SDK #

Open SDK downloads for the packages available on this installation. The page shows exact versions, archive checksums, and copyable installation commands. No Stampwing source checkout is required. If downloads are unavailable, use the dependency-free HTTP quickstart.

SDK downloads and installation commands →

2. Install in your own app #

Run the exact Node.js installation command from SDK downloads inside your application directory. For an archive you downloaded manually, pass its actual path to npm install. Keep the artifact available to your deployment builds. Use a .mjs file for these ES module examples.

Check the installed packageshell
npm ls @postrune/sdk
./node_modules/.bin/postrune --version

Copy the installation command →

3. Send and inspect a Test message #

Copy your private .env.stampwing from the quickstart into the consumer application folder and add .env.stampwing to that application’s .gitignore before copying the secret. The tutorial folder’s ignore rule does not protect a different folder. Run commands from the consumer folder and save this script there as send-test.mjs. The doctor call checks the key without sending and the guard refuses Live credentials or a different project. Keep STAMPWING_EXPECTED_PROJECT_ID from the quickstart. Use a key with email:send and email:read.

send-test.mjsjavascript
import { Postrune } from '@postrune/sdk';

const operationKey = process.env.STAMPWING_OPERATION_KEY;
const apiKey = process.env.STAMPWING_API_KEY;
const baseUrl = process.env.STAMPWING_BASE_URL;
const expectedProjectId = process.env.STAMPWING_EXPECTED_PROJECT_ID?.trim();
if (!operationKey || !apiKey || !baseUrl || !expectedProjectId) {
  throw new Error('Set the four POSTRUNE_ values from the quickstart.');
}
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(expectedProjectId)) {
  throw new Error('Set the expected project UUID from Settings.');
}
const client = new Postrune({ apiKey, baseUrl });
const check = await client.doctor();
if (!check.credential.valid || check.sent !== false || check.credential.environment !== 'test'
    || check.credential.projectId.toLowerCase() !== expectedProjectId.toLowerCase()) {
  throw new Error('This tutorial requires a verified Test credential for the expected project.');
}
for (const permission of ['email:send', 'email:read']) {
  if (!check.credential.permissions.includes(permission)) {
    throw new Error('Missing permission: ' + permission);
  }
}
const sent = await client.send({
  from: 'hello@stampwing.test',
  to: 'reader@example.com',
  subject: 'Your Stampwing integration is ready',
  text: 'This is a simulated Test message. No email is delivered.',
}, { idempotencyKey: operationKey });
console.log(sent); // Preserve this UUID even if the following read fails.
try {
  console.log(await client.getEmail(sent.id));
} catch {
  console.error('Send accepted as ' + sent.id + '. Status lookup failed; do not submit another message.');
  process.exitCode = 2;
}

4. Run it and understand retries #

This example deliberately uses the exact quickstart payload. With the same project, Test key, and saved operation key, it reads back the same message UUID instead of creating another email. If you used an older or edited quickstart payload, recover that exact payload first. Do not change the key just to bypass a conflict.

Expect the same { id, status, mode: "demo" } acceptance shape as the HTTP quickstart, followed by current delivery metadata. The SDK’s ordinary send method makes one attempt and has a 15-second deadline. A timeout is unconfirmed, not evidence of failure.

For a genuinely new authorized business event, save its new key and frozen content before the first send. If you choose sendWithRetry, supply that saved key and a bounded retry budget. Never generate a fresh key in each job attempt. PostruneError carries status, code, requestId, issues, and retryAfterMs when available; network failures can occur before a structured response exists.

Consumer application terminalshell
node --env-file=.env.stampwing send-test.mjs

5. Keep the Next.js integration on the server #

In Next.js, put STAMPWING_API_KEY, STAMPWING_BASE_URL, and STAMPWING_EXPECTED_PROJECT_ID in your private .env.local or deployment secret settings and restart the app after changing them. The standalone Node script uses --env-file; Next.js loads .env.local itself. Install server-only in the consumer app with npm install server-only if needed.

Save the following helper in src/lib/stampwing.ts (or lib/stampwing.ts if your app has no src directory). Call it from an authenticated server action, route handler, or durable worker only after your app authorizes the business event. The caller must supply a recipient from trusted application data and an operation key saved with that event.

src/lib/stampwing.ts — Test integration helpertypescript
import 'server-only';
import { Postrune } from '@postrune/sdk';

export async function sendWelcomeTest(event: {
  recipient: string; savedOperationKey: string;
}) {
  const apiKey = process.env.STAMPWING_API_KEY;
  const baseUrl = process.env.STAMPWING_BASE_URL;
  const expectedProjectId = process.env.STAMPWING_EXPECTED_PROJECT_ID?.trim();
  if (!apiKey || !baseUrl || !expectedProjectId) throw new Error('Stampwing is not configured.');
  const client = new Postrune({ apiKey, baseUrl });
  const check = await client.doctor();
  if (!check.credential.valid || check.sent !== false || check.credential.environment !== 'test'
      || check.credential.projectId.toLowerCase() !== expectedProjectId.toLowerCase()
      || !check.credential.permissions.includes('email:send')) {
    throw new Error('Use a Test sending credential for the expected project.');
  }
  return client.send({
    from: 'hello@stampwing.test', to: event.recipient,
    subject: 'Welcome to your app',
    text: 'Your Test integration is connected. Delivery is simulated.',
  }, { idempotencyKey: event.savedOperationKey });
}

6. Use a published template #

  1. Create a template in the same project and Test environment, declare its variables, and preview it using synthetic values.
  2. Publish a version and copy its version UUID. Draft IDs and version IDs are different; a send pins the published version.
  3. Give the sending key email:send and templates:use. Keep email:read if you also read progress.
  4. Replace raw subject/text/html with templateVersionId and variables. A request cannot mix the two forms.
After creating client and checking Test scope as abovejavascript
const templateVersionId = process.env.POSTRUNE_TEMPLATE_VERSION;
if (!templateVersionId) throw new Error('Set the published POSTRUNE_TEMPLATE_VERSION UUID.');
const result = await client.send({
  from: 'hello@stampwing.test', to: 'reader@example.com',
  templateVersionId,
  variables: { name: 'Ada' },
}, { idempotencyKey: 'template-tutorial:welcome:001' });

7. Verify webhook bytes before applying changes #

Create an HTTPS endpoint in Webhooks when your installation supports it. Store its signing secret on your server separately from the API key. Verify the original request text before parsing or handling the event. A JSON parser that runs first can change the bytes and break signature verification.

Return a non-2xx response if verification or durable storage fails. Expect duplicate and out-of-order events. A webhook replay repeats a notification; it does not resend the email. Your local loopback listener is not reachable from a hosted service. For an account-free exercise, use the signed local receiver tutorial.

Handler fragment — request and durable storage come from your applicationtypescript
import { verifyWebhook } from '@postrune/sdk';

const secret = process.env.POSTRUNE_WEBHOOK_SECRET;
if (!secret) throw new Error('Webhook verification is not configured.');
const rawBody = await request.text();
const event = await verifyWebhook(rawBody, request.headers, secret);
// Persist the verified event identity and intended work atomically.
// Only then acknowledge the request with a 2xx response.
// Apply business effects asynchronously and deduplicate by event identity.

Build and test a durable webhook receiver →

8. Use HTTP or another language #

HTTP works from any backend language: the request body, Bearer header, idempotency rules, and response contract are the same. The SDK is for Node.js and TypeScript; from other languages, call the API directly.

Read the HTTP fields and permissions →

Sources and further reading

Written for Stampwing with AI assistance and checked against the linked documentation. Examples are educational; simulated results are labelled. How these resources are maintained.