# Source: https://polar.sh/docs/integrate/sdk/adapters/nextjs.md

# Source: https://polar.sh/docs/guides/nextjs.md

> ## Documentation Index
> Fetch the complete documentation index at: https://polar.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrate Polar with Next.js

> In this guide, we'll show you how to integrate Polar with Next.js.

Feel free to use our quick-start script to get started inside a new Next.js project:

```bash Terminal theme={null}
# Inside a new Next.js project
npx polar-init
```

Consider following this guide while using the Polar Sandbox Environment. This will allow you to test your integration without affecting your production data.

[A complete code-example of this guide can be found on GitHub](https://github.com/polarsource/polar-next).

## Install the Polar JavaScript SDK

To get started, you need to install the Polar JavaScript SDK and the Polar Nextjs helper package. You can do this by running the following command:

```bash Terminal theme={null}
pnpm install @polar-sh/sdk @polar-sh/nextjs
```

## Setting up environment variables

### Polar Access Token

To authenticate with Polar, you need to create an access token, and supply it to Next.js using a `POLAR_ACCESS_TOKEN` environment variable.

You can create an organization access token from your organization settings.

## Configuring a Polar API Client

To interact with the Polar API, you need to create a new instance of the `Polar` class. This class uses the provided access token to authenticate with the Polar API.

```typescript  theme={null}
// src/polar.ts
import { Polar } from "@polar-sh/sdk";

export const api = new Polar({
  accessToken: process.env.POLAR_ACCESS_TOKEN!,
  server: "sandbox", // Use this option if you're using the sandbox environment - else use 'production' or omit the parameter
});
```

Remember to replace `sandbox` with `production` when you're ready to switch to the production environment.

## Generating Polar Checkout Sessions

Next up, we need to create a checkout endpoint to handle the creation of checkout sessions.

Go ahead and create a new GET route in Next.js.

```typescript  theme={null}
// src/app/checkout/route.ts
import { Checkout } from "@polar-sh/nextjs";

export const GET = Checkout({
  accessToken: process.env.POLAR_ACCESS_TOKEN!,
  successUrl: "https://your-app.com/confirmation?checkout_id={CHECKOUT_ID}",
  server: "sandbox", // Use this option if you're using the sandbox environment - else use 'production' or omit the parameter
});
```

## Handling Polar Webhooks

Polar can send you events about various things happening in your organization. This is very useful for keeping your database in sync with Polar checkouts, orders, subscriptions, etc.

Configuring a webhook is simple. Head over to your organization's settings page and click on the "Add Endpoint" button to create a new webhook.

### Tunneling webhook events to your local development environment

If you're developing locally, you can use a tool like [ngrok](https://ngrok.com/) to tunnel webhook events to your local development environment. This will allow you to test your webhook handlers without deploying them to a live server.

Run the following command to start an ngrok tunnel:

```bash Terminal theme={null}
ngrok http 3000
```

### Add Webhook Endpoint

1. Point the Webhook to `your-app.com/api/webhook/polar`. This must be an absolute URL which Polar can reach. If you use ngrok, the URL will look something like this: `https://<your-ngrok-id>.ngrok-free.app/api/webhook/polar`.
2. Select which events you want to be notified about. You can read more about the available events in the [Events section](/api-reference#webhooks).
3. Generate a secret key to sign the requests. This will allow you to verify that the requests are truly coming from Polar.
4. Add the secret key to your environment variables.

```bash Terminal theme={null}
# .env
POLAR_ACCESS_TOKEN="polar_pat..."
POLAR_WEBHOOK_SECRET="..."
```

### Setting up the Webhook handler

```typescript  theme={null}
// src/app/api/webhook/polar/route.ts
import { Webhooks } from "@polar-sh/nextjs";

export const POST = Webhooks({
	webhookSecret: process.env.POLAR_WEBHOOK_SECRET,
	onPayload: async (payload) => // Handle payload...
});
```

The webhook event is now verified and you can proceed to handle the payload data.

### Handling Webhook Events

Depending on which events you've subscribed to, you'll receive different payloads. This is where you can update your database, send notifications, etc.

```typescript  theme={null}
// src/app/api/webhook/polar/route.ts
import { Webhooks } from "@polar-sh/nextjs";

export const POST = Webhooks({
  webhookSecret: process.env.POLAR_WEBHOOK_SECRET,
  onPayload: async (payload) => ...,
  onOrderCreated: async (order) => ...,
  onCustomerStateChanged: async (customerState) => ...,
  ...
});
```

### Notifying the client about the event

If you're building a real-time application, you might want to notify the client about the event. On the confirmation-page, you can listen for the `checkout.updated` event and update the UI accordingly when it reaches the succeeded status.

## Conclusion

If you have issues or need support, feel free to join [our Discord](https://discord.gg/Pnhfz3UThd).