# Next.js

This guide adds OnCharge to a Next.js (App Router) store: a server action creates the checkout session, a client component embeds the checkout, a route handler receives webhooks, and an admin action reports shipments. It uses `@oncharge/node` and `@oncharge/js`.

> **Coming soon to npm.** `@oncharge/node` and `@oncharge/js` are not yet published. Until they are, use the dependency-free [`onchargeRequest()` helper](https://oncharge.io/docs/authentication#nodejs), the [webhook verifier](https://oncharge.io/docs/webhooks#nodejs) and the [plain iframe component](#without-the-sdks) at the end of this page.

## Environment

```bash title=".env.local"
ONCHARGE_API_KEY=oc_key_...
ONCHARGE_API_SECRET=oc_sec_...
ONCHARGE_WEBHOOK_SECRET=oc_cbsec_...
```

Never prefix these with `NEXT_PUBLIC_`: that would ship them to the browser.

## 1. A server-only client

```ts title="lib/oncharge.ts"
import 'server-only';
import { OnCharge } from '@oncharge/node';

export const oncharge = new OnCharge({
  apiKey: process.env.ONCHARGE_API_KEY!,
  apiSecret: process.env.ONCHARGE_API_SECRET!,
});
```

## 2. Create the session on the server

Compute the amount from your own database, never from the browser.

```ts title="app/checkout/[orderId]/page.tsx"
import { oncharge } from '@/lib/oncharge';
import { getOrder } from '@/lib/orders';
import { CheckoutFrame } from './checkout-frame';

export const dynamic = 'force-dynamic';

export default async function CheckoutPage({ params }: { params: Promise<{ orderId: string }> }) {
  const { orderId } = await params;
  const order = await getOrder(orderId);

  const session = await oncharge.checkout.sessions.create(
    {
      amount: order.totalCents,
      currency: 'USD',
      reference: `order-${order.id}`,
      order_id: order.id,
      return_url: `https://shop.example.com/checkout/${order.id}/complete`,
      customer_email: order.email,
      shipping: order.requiresShipping
        ? {
            name: order.shipping.name,
            line1: order.shipping.line1,
            line2: order.shipping.line2,
            city: order.shipping.city,
            state: order.shipping.state,
            postal_code: order.shipping.postalCode,
            country: order.shipping.country,
          }
        : undefined,
    },
    { idempotencyKey: `order-${order.id}` },
  );

  await saveSessionId(order.id, session.session_id);
  return <CheckoutFrame url={session.checkout_url} orderId={order.id} />;
}
```

The same idempotency key returns the same open session if the page is reloaded within 50 minutes.

These pages are written for Next.js 15, where `params` is a promise. On Next.js 14, `params` is a plain object: type it as `{ orderId: string }` and read `params.orderId` without `await`.

## 3. Embed the checkout

```tsx title="app/checkout/[orderId]/checkout-frame.tsx"
'use client';

import { useRouter } from 'next/navigation';
import { OnChargeCheckout } from '@oncharge/js/react';

export function CheckoutFrame({ url, orderId }: { url: string; orderId: string }) {
  const router = useRouter();
  return (
    <OnChargeCheckout
      url={url}
      minHeight={480}
      onComplete={() => router.push(`/checkout/${orderId}/complete`)}
      onRedirect={({ url: target }) => window.location.assign(target)}
      onError={(error) => console.warn('OnCharge checkout error', error)}
    />
  );
}
```

Prefer a full-page redirect? Replace the component with `redirect(session.checkout_url)` from `next/navigation` in the page.

## 4. Receive webhooks

```ts title="app/api/webhooks/oncharge/route.ts"
import { createWebhookHandler } from '@oncharge/node/next';
import { markOrderPaid, markOrderFailed, recordRefund, flagOrder } from '@/lib/orders';

export const { POST } = createWebhookHandler({
  secret: process.env.ONCHARGE_WEBHOOK_SECRET!,
  async onEvent(event) {
    const orderId = event.data.order_id;
    switch (event.type) {
      case 'payment.captured':
        await markOrderPaid(orderId, event.data.session_id);
        break;
      case 'payment.refused':
      case 'payment.cancelled':
        await markOrderFailed(orderId);
        break;
      case 'refund.succeeded':
        await recordRefund(orderId, event.data.amount);
        break;
      case 'chargeback.opened':
        await flagOrder(orderId);
        break;
    }
  },
});
```

Register `https://shop.example.com/api/webhooks/oncharge` as the store's webhook URL in the merchant portal. The handler skips repeated event IDs in memory; on serverless or with several instances, pass `eventIdStore: { has(id), add(id) }` backed by your database so a retry that lands on another instance is still recognised.

## 5. The return page

```tsx title="app/checkout/[orderId]/complete/page.tsx"
import { getOrder } from '@/lib/orders';

export const dynamic = 'force-dynamic';

export default async function Complete({ params }: { params: Promise<{ orderId: string }> }) {
  const { orderId } = await params;
  const order = await getOrder(orderId);
  return order.paid ? <p>Thank you! Your order is confirmed.</p> : <p>We are confirming your payment. This page will update shortly.</p>;
}
```

`order.paid` is set by the webhook. To check without waiting, call `oncharge.checkout.sessions.retrieve(sessionId)` with the saved session ID.

## 6. Report shipments

```ts title="app/admin/orders/actions.ts"
'use server';
import { oncharge } from '@/lib/oncharge';

export async function markShipped(orderId: string, carrier: string, trackingNumber: string) {
  const result = await oncharge.shipments.report({
    order_id: orderId,
    shipments: [{ carrier, tracking_number: trackingNumber }],
  });
  const rejected = result.shipments.filter((s) => s.status === 'rejected');
  if (rejected.length) throw new Error(rejected.map((s) => s.message).join('; '));
}
```

## 7. Refunds

```ts
await oncharge.refunds.create({ session_id: sessionId, amount: 1500, currency: 'USD', reference: `refund-${refundId}` });
```

## 8. RUO stores: the compliance feed

```ts title="app/.well-known/oncharge-compliance/[route]/route.ts"
import { createComplianceFeedRoute } from '@oncharge/node/next';
import { listPublishedCatalog } from '@/lib/catalog';

export const dynamic = 'force-dynamic';

export const { GET } = createComplianceFeedRoute({
  connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
  host: 'shop.example.com',
  site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
  listItems: async ({ cursor, limit }) => listPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
});
```

See [RUO compliance feed](https://oncharge.io/docs/compliance-feed).

## Content Security Policy

If you set a CSP in `next.config.js` or middleware, allow the checkout frame:

```js title="next.config.js"
const csp = ["frame-src 'self' https://app.oncharge.io"].join('; ');

module.exports = {
  async headers() {
    return [{ source: '/checkout/:path*', headers: [{ key: 'Content-Security-Policy', value: csp }] }];
  },
};
```

## Without the SDKs

Until the packages are published, this client component replaces `OnChargeCheckout`:

```tsx title="app/checkout/[orderId]/checkout-frame.tsx"
'use client';

import { useEffect, useMemo, useRef, useState } from 'react';

export function CheckoutFrame({ url, orderId }: { url: string; orderId: string }) {
  const frame = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(480);
  const [src, setSrc] = useState<string | null>(null);
  const nonce = useMemo(() => Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join(''), []);

  useEffect(() => {
    const checkout = new URL(url);
    checkout.searchParams.set('embed', '1');
    checkout.searchParams.set('parent_origin', window.location.origin);
    checkout.searchParams.set('embed_nonce', nonce);
    setSrc(checkout.toString());

    function onMessage(event: MessageEvent) {
      if (event.origin !== checkout.origin || event.source !== frame.current?.contentWindow) return;
      const msg = event.data;
      if (!msg || msg.source !== 'oncharge-checkout' || msg.version !== 1 || msg.nonce !== nonce) return;
      if ((msg.type === 'ready' || msg.type === 'resize') && typeof msg.height === 'number') setHeight(Math.max(480, Math.ceil(msg.height)));
      if (msg.type === 'complete') window.location.href = `/checkout/${orderId}/complete`;
      if (msg.type === 'redirect' && typeof msg.url === 'string') window.location.assign(msg.url);
    }
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, [url, orderId, nonce]);

  if (!src) return null;
  return <iframe ref={frame} src={src} title="Secure checkout" allow="payment" referrerPolicy="origin" style={{ width: '100%', height, border: 0 }} />;
}
```

On the server, `session.checkout_url` becomes `new URL(session.iframe_url, 'https://app.oncharge.io').href`.
