Astroをベースとしたプロジェクト(Cloudflare Pagesへのデプロイを想定)で、KindeとStripeを組み合わせて月額サブスクリプション機能を構築する具体的な手順を解説します。
まず、関連するスキルファイルを確認します。構成の全体図と詳細な手順を作成します。—
全体の流れ
ユーザーが登録 → Kinde でログイン → Stripe で課金 → D1 にプラン状態を保存 → ページアクセス時に Middleware がプランを確認してルーティングする、というシンプルな構成です。
Step 1 — プロジェクト作成
npm create cloudflare@latest my-saas -- --framework astro
cd my-saas
wrangler.toml の compatibility_flags に nodejs_compat を追加します。
[compatibility_flags]
compatibility_flags = ["nodejs_compat"]
Step 2 — Kinde の設定(認証)
Kinde ダッシュボードでアプリ作成
- kinde.com でアカウント作成
- Applications → Add application → 「Back-end web」を選択
- Callback URL:
http://localhost:4321/api/auth/kinde_callback
- Logout URL:
http://localhost:4321
パッケージインストール
npm install @kinde-oss/kinde-typescript-sdk
環境変数(.dev.vars / Cloudflare Secrets)
KINDE_DOMAIN=https://your-subdomain.kinde.com
KINDE_CLIENT_ID=xxx
KINDE_CLIENT_SECRET=xxx
KINDE_REDIRECT_URI=http://localhost:4321/api/auth/kinde_callback
KINDE_LOGOUT_REDIRECT_URI=http://localhost:4321
認証ルート作成
src/pages/api/auth/
login.ts → Kinde の認証URLへリダイレクト
kinde_callback.ts → コールバック処理・セッション保存
logout.ts → ログアウト
// src/pages/api/auth/login.ts
import type { APIRoute } from "astro";
import { createKindeServerClient, GrantType } from "@kinde-oss/kinde-typescript-sdk";
export const GET: APIRoute = async ({ request, redirect, locals }) => {
const client = createKindeServerClient(GrantType.AUTHORIZATION_CODE, {
authDomain: import.meta.env.KINDE_DOMAIN,
clientId: import.meta.env.KINDE_CLIENT_ID,
clientSecret: import.meta.env.KINDE_CLIENT_SECRET,
redirectURL: import.meta.env.KINDE_REDIRECT_URI,
logoutRedirectURL: import.meta.env.KINDE_LOGOUT_REDIRECT_URI,
});
const loginUrl = await client.login(sessionManager); // sessionManager は Cookie ベースで実装
return redirect(loginUrl.toString());
};
Step 3 — Cloudflare D1 セットアップ
wrangler d1 create saas-db
wrangler.toml にバインドを追加: