> Add Plandalf to the App Router or Pages Router with next/script or the React provider.

Source: https://plandalf.com/docs/frameworks/nextjs

Frameworks

# Next.js

Load the hosted script with `next/script` to open checkouts from HTML attributes. To use hooks in the App Router or Pages Router, install the [React package](#the-plandalf-react-package).

## Add the script

1.  ### Install the SDK + use data attributes
    
    The SDK auto-discovers any element with the canonical data attributes — even ones React renders later.
    
    ```tsx
    // app/layout.tsx — App Router
    import Script from 'next/script';
    
    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html>
          <body>
            {children}
            <Script src="https://YOUR-ORG.plandalf.dev/js/plandalf-sdk.js" strategy="afterInteractive" />
          </body>
        </html>
      );
    }
    
    // Anywhere in your app
    export function BuyButton() {
      return (
        <button
          data-plandalf-present="YOUR-CHECKOUT"
          className="bg-blue-600 text-white px-6 py-3 rounded-lg"
        >
          Buy Now
        </button>
      );
    }
    ```
    
2.  ### Make the first open instant (optional)
    
    Paste this under the SDK script tag on the pages that hold the trigger. It fetches the checkout UI (about 1.2 MB) in the background while the page sits idle, so the click only pays for creating the session. Leave it off pages with no checkout: visitors download it whether or not they buy. In a React app, call sdk.preload('checkout') from the ready callback in an effect instead.
    
    ```html
    <script>
      // Optional: fetch the checkout UI while the page is idle, so the first click opens at once.
      window.plandalf = window.plandalf || function () { (window.plandalf.q = window.plandalf.q || []).push(arguments); };
      plandalf('ready', (sdk) => sdk.preload('checkout'));
    </script>
    ```
    

**Tip**

For programmatic control: plandalf.present('YOUR-CHECKOUT') returns a FlowHandle (a Promise, plus .events and .close()).

### App Router

Add the script inside `<body>` in `app/layout.tsx`. The layout can stay a server component: `next/script` handles loading in the browser.

```tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://YOUR-ORG.plandalf.dev/js/plandalf-sdk.js" strategy="afterInteractive" />
      </body>
    </html>
  );
}
```

### Pages Router

Render the same script in `pages/_app.tsx`. An app using both routers needs both.

```tsx
import type { AppProps } from "next/app";
import Script from "next/script";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Script src="https://YOUR-ORG.plandalf.dev/js/plandalf-sdk.js" strategy="afterInteractive" />
    </>
  );
}
```

Use `afterInteractive` or `lazyOnload`, not `worker`: the script needs the page, which a web worker can't reach.

## Open a checkout from a button

Add the attribute to any element. Server components can render it, since it needs no JavaScript of its own:

```tsx
export default function Pricing() {
  return <button data-plandalf-present="YOUR-CHECKOUT">Buy Now</button>;
}
```

### From your own click handler

Click handlers need a client component. This helper queues calls made before the script loads:

```ts
type Plandalf = ((...args: unknown[]) => void) & { q?: unknown[][] };

declare global {
  interface Window {
    plandalf?: Plandalf;
  }
}

export function plandalf(...args: unknown[]): void {
  if (typeof window === "undefined") return; // nothing to do on the server
  // Hold calls made before the script loads; it runs them when it arrives.
  window.plandalf ??= function (...a: unknown[]) {
    (window.plandalf!.q ??= []).push(a);
  } as Plandalf;
  window.plandalf(...args);
}
```

```tsx
"use client";

import { plandalf } from "@/lib/plandalf";

export function UpgradeButton() {
  return <button onClick={() => plandalf("present", "YOUR-CHECKOUT")}>Upgrade</button>;
}
```

See [Open a checkout from code](https://plandalf.com/docs/developers/open-a-checkout).

## Show a checkout on the page

Render an empty element with `data-plandalf-mount`, on a page such as `app/checkout/page.tsx`:

```tsx
export default function CheckoutPage() {
  return <div data-plandalf-mount="YOUR-CHECKOUT" style={{ minHeight: 480 }} />;
}
```

## Show a deadline timer

Render an empty element with your deadline timer's slug. The script draws the live countdown inside it. To charge the deadline timer's current price, add `data-plandalf-apply-promo` with the same slug to your buy button.

```tsx
<div data-plandalf-promo="YOUR-PROMO" />
<button data-plandalf-present="YOUR-CHECKOUT" data-plandalf-apply-promo="YOUR-PROMO">Buy Now</button>
```

See [Countdowns](https://plandalf.com/docs/promos/countdowns).

## The @plandalf/react package

To open checkouts with React hooks, install the package in your app.

```bash
npm install @plandalf/react
```

### App Router

The package starts with `'use client'`, so you can render the provider in `app/layout.tsx` and keep the layout as a server component.

```tsx
import { PlandalfProvider } from '@plandalf/react';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <PlandalfProvider apiBase="https://YOUR-ORG.plandalf.dev">{children}</PlandalfProvider>
      </body>
    </html>
  );
}
```

Call hooks such as `usePresent()` in a file that starts with `'use client'`. If you pass a function to the provider, such as a getter for a `metadata` value, define it in your own client wrapper.

### Pages Router

In `pages/_app.tsx`, import the same provider and wrap `<Component {...pageProps} />` in it. See [React components and hooks](https://plandalf.com/docs/developers/react) for a buy button that uses the provider.

## Check it's working

1.  ### Run the app
    
    If you used the hosted script, type `typeof window.plandalf` in the browser console. Look for `"function"`.
    
2.  ### Click your button
    
    Plandalf should display your checkout over the page. Navigate to another page and back, and check the button still works.
    
3.  ### Make a test purchase
    
    Add `localhost` and your preview domain, such as `*.vercel.app`, in Plandalf under **Settings → Advanced → Test domains**. Checkouts there use Stripe test cards. See [Test mode](https://plandalf.com/docs/get-started/test-mode).
    

## If it isn't working

-   A `window is not defined` error means code touched `window` during server rendering. Call Plandalf only from event handlers or effects in client components, or use the helper above.
-   If your app sends a Content Security Policy, allow `https://*.plandalf.dev` and `https://js.stripe.com` in `script-src`, `connect-src` and `frame-src`, and pass your nonce to `<Script>`.
-   Add `data-debug="true"` to the `<Script>` and the console logs each step the script takes.

See [Troubleshooting](https://plandalf.com/docs/help/troubleshooting).

Something wrong or missing? Email [hello@plandalf.com](mailto:hello@plandalf.com).
