Polar + Encore

Payments and subscriptions.
From the first deploy.

Polar handles subscriptions, payments, and tax compliance. Encore handles the infrastructure and observability around it. The billing infrastructure most teams build over months, you start with it.

$ encore app create --example=ts/polar

What is ?

Encore is an open source TypeScript backend framework. You define your infrastructure (databases, queues, cron jobs, API endpoints) directly in your application code using the Encore SDK.

Encore understands your app's architecture and uses it to run your app locally, provision cloud infrastructure (in your AWS or GCP account), and give you observability like distributed tracing and service catalogs, all without config files or boilerplate.

Learn more about Encore →

What Polar + Encore gives you

The infrastructure you'd eventually build around payments (managed database, secrets per environment, preview environments, tracing) already done, in your AWS or GCP account.

Polar

Polar handles monetization

Subscriptions, one-time payments, license keys, usage-based pricing. Global tax compliance as Merchant of Record.

Deploy to your own AWS or GCP

Start free on Encore Cloud. When you're ready, connect your own AWS or GCP account and Encore deploys there instead. No code changes.

AWSGCP

Trace every request

Every API call and webhook gets a visual timeline showing what happened, how long it took, and where it failed.

Preview environments

Every pull request gets a full copy of your backend with its own database and secrets. Test payments with Polar sandbox before merging.

Git push to deploy

Push to main and your app is live. No CI/CD pipelines to configure, no Dockerfiles to write.

Databases included

Define a database in TypeScript and Encore creates PostgreSQL for you, locally and in the cloud. Migrations run automatically on deploy.

Secrets management

Store API tokens and webhook secrets in Encore instead of .env files. Each environment (local, preview, production) has its own values.

From code to cloud in minutes

Write TypeScript. Encore handles the infrastructure. No DevOps expertise required.

1

Configure the Polar SDK

Initialize the Polar client with your access token stored as an Encore secret. Secrets are encrypted per environment and injected at runtime.

billing/polar.ts
import { Polar } from "@polar-sh/sdk";
import { secret } from "encore.dev/config";

const accessToken = secret("POLAR_ACCESS_TOKEN");

export const polar = new Polar({
  accessToken: accessToken(),
  // Use "sandbox" for development
  server: "production",
});
2

Create a checkout endpoint

Define a type-safe API endpoint that creates Polar checkout sessions. Customers are sent to Polar's hosted payment page. Polar handles the entire payment flow.

billing/checkout.ts
import { api } from "encore.dev/api";
import { polar } from "./polar";

interface CheckoutRequest {
  productId: string;
  customerEmail: string;
}

interface CheckoutResponse {
  checkoutUrl: string;
}

export const createCheckout = api(
  { expose: true, method: "POST", path: "/checkout" },
  async (req: CheckoutRequest): Promise<CheckoutResponse> => {
    const checkout = await polar.checkouts.custom.create({
      productId: req.productId,
      customerEmail: req.customerEmail,
      successUrl: "https://yourapp.com/success",
    });

    return { checkoutUrl: checkout.url };
  }
);
3

Handle webhooks

Receive real-time events when customers subscribe, pay, or cancel using a raw endpoint. The SDK validates webhook signatures automatically. Every webhook is traced so you can see exactly what happened.

billing/webhook.ts
import { api } from "encore.dev/api";
import { secret } from "encore.dev/config";
import {
  validateEvent,
  WebhookVerificationError
} from "@polar-sh/sdk/webhooks";

const webhookSecret = secret("POLAR_WEBHOOK_SECRET");

export const webhook = api.raw(
  { expose: true, method: "POST", path: "/webhook/polar" },
  async (req, res) => {
    const body = await readBody(req);

    try {
      const event = validateEvent(
        body,
        req.headers,
        webhookSecret()
      );

      switch (event.type) {
        case "subscription.active":
          await activateSubscription(event.data);
          break;
        case "subscription.canceled":
          await cancelSubscription(event.data);
          break;
        case "order.paid":
          await fulfillOrder(event.data);
          break;
      }

      res.writeHead(200);
      res.end();
    } catch (err) {
      if (err instanceof WebhookVerificationError) {
        res.writeHead(403);
        res.end("Invalid signature");
        return;
      }
      throw err;
    }
  }
);

Debug payment flows instantly

Every webhook, checkout, and API call is automatically traced. See the full request flow from Polar's webhook to your database, locally and in production. No instrumentation code to write.

Learn more about tracing →

What you don't have to build

The boring, error-prone work that Polar and Encore eliminate.

Payment processingPolar
Tax calculation & compliancePolar
Invoice generationPolar
Subscription lifecyclePolar
Customer billing portalPolar
Payout handlingPolar
Database provisioningEncore
Secrets & credentialsEncore
CI/CD pipelineEncore
Preview environmentsEncore
TLS certificatesEncore
Distributed tracingEncore
Cloud IAM & networkingEncore
Load balancingEncore
Container orchestrationEncore

You focus on your product. That's it.

Build your Polar + Encore backend with AI

Because Encore defines infrastructure in code and provides built-in distributed tracing, AI coding assistants like Claude and Cursor can build and debug your entire Polar integration end-to-end.

They can read your Encore services to understand checkout flows and webhook handlers, then inspect traces to diagnose exactly what happened when a Polar checkout completes or a subscription webhook arrives.

When you're ready for your own cloud

Connect your AWS or GCP account and deploy. Encore provisions the infrastructure directly in your account: databases, load balancers, IAM roles, networking. Same code you've been running on Encore Cloud.

You can see it all in your console. Customer data stays in your infrastructure. Full control when you need it.

Learn how cloud deployment works →

What you get in your own cloud

Declare what you need in TypeScript. Encore provisions it in your AWS or GCP account.

Databases

RDS or Cloud SQL for subscriptions, customers, and entitlements.

Secrets

AWS Secrets Manager or GCP Secret Manager for API tokens.

Pub/Sub

SQS or GCP Pub/Sub for async webhook processing.

Cron Jobs

CloudWatch or Cloud Scheduler for subscription sync and reminders.

Load Balancer & TLS

ALB or Cloud Load Balancing with automatic certificates.

Object Storage

S3 or Cloud Storage for invoices and downloadable content.

IAM & Networking

Proper IAM roles, VPCs, and security groups by default.

Observability

Distributed tracing, metrics, and logging out of the box.

Trusted by teams at
GrouponPaveBookshop.orgCoinbase

Start building today

Free to start. Your own AWS or GCP when you're ready.