🕌

【NextJs + BetterAuth + Polar】Subcription サブスクサービスの実装【#10 Polar】

に公開

【#10 Polar】
YouTube: https://youtu.be/hrJrl4IlQb0
https://youtu.be/hrJrl4IlQb0

今回はPolarを使用して商品を作成していきます。

https://polar.sh/

サインアップして最初のプロジェクトを作成したら、
ダッシュボードに移動後、サイドバーの最下部の
プロジェクト名をクリックして、sandbox版を表示します。

再度sandbox版でプロジェクトを作成したら、
商品を作成していきます。

.env
DATABASE_URL="postgresql://neondb_owner:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

BETTER_AUTH_SECRET="Ahl8Nnxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
BETTER_AUTH_URL="http://localhost:3000"

POLAR_ACCESS_TOKEN="polar_oat_TYxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
POLAR_SUCCESS_URL="http://localhost:3000"

作成した商品のIDとslugをauth.tsに設定します。

lib/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { polar, checkout, portal } from "@polar-sh/better-auth";

import { db } from "@/src"; // your drizzle instance
import * as schema from "@/src/db/schema";

import { polarClient } from "./polar-client";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg", // or "mysql", "sqlite"
    schema: {
      ...schema,
    },
  }),
  emailAndPassword: {
    enabled: true,
  },
  plugins: [
    polar({
      client: polarClient,
      createCustomerOnSignUp: true,
      use: [
        checkout({
          products: [
            {
              productId: "eb469086-9063-4de8-af37-389712e689fd",
              slug: "test-product",
            },
          ],
          successUrl: process.env.POLAR_SUCCESS_URL,
          authenticatedUsersOnly: true,
        }),
        portal(),
      ],
    }),
  ],
});

Discussion