How I built a paid membership site with Astro and Convex

By

Tagged: Astro

Build a paid membership site with Astro SSR, Convex, Resend magic links, Paddle Classic webhooks, and Cloudflare Workers. Step-by-step walkthrough.

Instead of building another one-off product site, I wanted a reusable membership starter I could drop into future projects. The goal was straightforward: sell access once, let members log in without passwords, gate Markdown content on the server, and accept payments through a webhook I could trust.

I pulled all of that plumbing into a generic project called Astro Membership Starter. It runs Astro with SSR on Cloudflare Workers, stores membership data in Convex, sends login emails through Resend, and handles payments with Paddle Classic. (I compared Paddle against other options in the payment providers hub.)

This tutorial walks through how I built it, stage by stage.

The problem I was solving

A paid membership site needs more than a checkout button.

You need:

  • a member record
  • a login flow that doesn’t leak who paid
  • sessions that survive page loads
  • content that stays hidden from logged-out visitors
  • webhook handling that copes with payment events arriving twice
  • a deployment model that runs server routes at the edge

You can bolt these pieces onto a static marketing site, but it gets messy fast. Auth logic drifts into client code, member-only Markdown ends up in the public bundle, and webhook handlers turn into copy-pasted snippets with ad-hoc secret checks.

I wanted everything in one small codebase where each part has a clear job.

Architecture before code

Here’s the shape I settled on:

PaymentsMembersHTTP-only sessioncookieBrowserAstro SSR routes onCloudflare WorkersConvex: users,sessions, magiclinks, paymentsResend: magic link +welcome emailPaddle ClassicPOST /api/purchaseVerify signatureConvex: activate /revoke memberResend: welcomeemail

The setup relies on three rules:

  1. SSR gating. The server decides whether to render preview Markdown or the full body, so member-only text never ships in logged-out HTML.
  2. A server secret. Astro API routes call Convex with AUTH_SERVER_SECRET, and public clients never get that key.
  3. Webhook verification. The handler rejects Paddle payloads unless the Classic signature checks out.

Each tool sticks to one job: Convex holds the data, Astro handles rendering and HTTP, Resend sends email, and Paddle acts as the billing system of record. Because of that split, I can swap out Resend or replace Paddle Classic without touching the content model.

Create the project

Start with a minimal Astro project:

npm create astro@latest astro-membership-starter -- --template minimal
cd astro-membership-starter
npx astro add cloudflare
npm install convex resend gray-matter sharp

Then create .env.example to document the required variables and .env.local for your real values:

touch .env.example .env.local

The starter targets Node.js 22 or newer, and Astro runs on port 4321 locally.

If you’re new to Astro SSR, the free Astro course covers pages, layouts, and deployment basics. For Workers specifically, read Cloudflare Workers first.

Stage 1: Astro SSR shell on Cloudflare

The site uses server output instead of a static build:

import { defineConfig } from 'astro/config'
import cloudflare from '@astrojs/cloudflare'

export default defineConfig({
  output: 'server',
  adapter: cloudflare({
    imageService: 'compile',
  }),
  server: {
    port: 4321,
  },
})

Every auth route, webhook route, and gated content page runs on the server. That’s non-negotiable for membership gating, since a static export would either push access checks to the client or force you to maintain a separate API service.

Cloudflare Workers fit this model well because the @astrojs/cloudflare adapter compiles Astro into a single Worker that serves both the SSR HTML and the API endpoints.

The tradeoff is that you pay for Worker invocations and manage secrets with Wrangler. That’s usually fine for a membership library with moderate traffic, though a huge public blog with almost no dynamic routes would probably be cheaper as a static site paired with a small API.

Stage 2: Flat Convex schema with indexed relations

Convex stores four tables:

users          // email, isActive, optional paddleCustomerId
sessions       // token, userId, expiresAt
magicLinks     // email, token, expiresAt, used
payments       // userId, paddleOrderId, amount, status

Each table stays flat, linking records with Convex IDs instead of nesting documents. Indexes cover the lookup paths the app queries:

users.by_email
users.by_paddleCustomerId
sessions.by_token
sessions.by_userId
magicLinks.by_token
payments.by_userId

I kept the schema small on purpose. Most membership sites need users, sessions, and payment history right away, while forums, comments, and audit logs can wait until you need them.

You can add tables like accessRequests, teams, or roles later when the product calls for them. Out of the box, the starter stops at a single isActive flag.

This is a poor fit for multi-tenant B2B with complex RBAC, per-seat billing, or heavy analytics inside the same database. Convex can handle that, but this starter will feel tight quickly.

Stage 3: Server-secret boundary

Convex functions are callable from the public internet unless you guard them.

Every server-only query and mutation in the starter takes serverSecret and calls requireServerSecret():

export function requireServerSecret(serverSecret: string) {
  const expected = process.env.AUTH_SERVER_SECRET

  if (!expected || serverSecret !== expected) {
    throw new Error('Unauthorized')
  }
}

Astro reads the same value through getAuthServerSecret() and passes it on every Convex call from API routes and middleware.

The Astro Worker is trusted backend code, whereas the browser isn’t. Without this check, anonymous clients could call your Convex functions directly to list members or create sessions.

Set the secret in two places:

# local Astro
AUTH_SERVER_SECRET=replace-with-a-long-random-value

# Convex deployment
npx convex env set AUTH_SERVER_SECRET replace-with-a-long-random-value

Keep both values identical, or login will work in one environment and fail in the other.

This gives you service-to-service shared-secret auth rather than end-user JWT validation inside Convex, which is plenty for a starter like this. If you expose Convex directly to browsers later on, add proper Convex auth or keep sensitive mutations behind your server routes.

I skipped password login in favor of short-lived magic links sent by email.

The login form posts to /api/auth/send. The route:

  1. normalizes the email
  2. loads the user with getLoginUserByEmail
  3. returns { ok: true } early when the user is missing or inactive
  4. creates a magic link token in Convex
  5. sends the email through Resend

The generic response is there so an attacker can’t probe which emails bought access.

For active members, the route generates a random token and stores it:

const token = crypto.randomBytes(32).toString('hex')

await convex.mutation(anyApi.auth.createMagicLink, {
  email,
  token,
  serverSecret,
})

Then it builds a login URL and sends the HTML email:

const loginUrl = new URL('/api/auth/verify', getSiteUrl(new URL(request.url)))
loginUrl.searchParams.set('token', token)
loginUrl.searchParams.set('next', next)

await new Resend(resendKey).emails.send({
  from: getEmailFrom(),
  to: email,
  subject: `Your ${SITE_NAME} login link`,
  html: `<p>Use this link to log in:</p><p><a href="${loginUrl}">${loginUrl}</a></p>`,
})

Configure EMAIL_FROM with a verified Resend domain, for example members@your-domain.com.

On the frontend, the login page uses HTMX so the form submits without a full page reload and shows the same generic confirmation message either way: “If that account is active, check your inbox.”

Stage 5: Scanner-safe confirmation

Email security scanners follow links before the human does. If the first GET consumed the token, real members would hit an expired link.

The verify route uses a two-step flow:

GET /api/auth/verify?token=...        -> confirmation HTML page
GET /api/auth/verify?token=...&confirm=1 -> create session, redirect

The first visit renders a simple confirmation page with a “Log in” link, and only clicking through that second step creates the session.

Inside verifyMagicLink, the token is marked used and checked against expiry:

if (!magicLink || magicLink.used || magicLink.expiresAt < args.now) {
  return null
}

await ctx.db.patch(magicLink._id, { used: true })

Magic links expire after 30 minutes, and sessions last 30 days.

It adds one extra click after opening the email, which is a fair trade for logins that work reliably in corporate inboxes.

Stage 6: HTTP-only sessions in middleware

After confirmation, the verify route creates a session row in Convex and sets two cookies:

cookies.set('session_token', sessionToken, { httpOnly: true, ... })
cookies.set('logged_in', '1', { httpOnly: false, ... })

session_token is the real credential, while logged_in is just a readable marker for UI toggles. Never trust logged_in for authorization.

src/middleware.ts loads the member on every request:

const user = await getConvexClient().query(anyApi.auth.getSessionUser, {
  token: sessionToken,
  now: Date.now(),
  serverSecret: getAuthServerSecret(),
})

if (user?.isActive) {
  context.locals.user = {
    _id: user.userId,
    email: user.email,
    name: user.name,
    isActive: user.isActive,
  }
} else {
  context.cookies.delete('session_token', { path: '/' })
  context.cookies.delete('logged_in', { path: '/' })
}

If the session expired or the member was revoked, the middleware deletes the stale cookies.

This follows the same idea as Astro middleware execution order. Because middleware runs before the page renders, gated routes read Astro.locals.user instead of touching cookies directly.

Logout deletes the Convex session server-side and clears both cookies.

Stage 7: Local Markdown loader and SSR gating

Member content lives as plain Markdown:

src/content/guides/
src/content/articles/

Each file requires title, description, and preview in frontmatter, and the loader reads them at build time with import.meta.glob:

const guideFiles = import.meta.glob<string>('../content/guides/*.md', {
  eager: true,
  query: '?raw',
  import: 'default',
})

The guide route chooses what to render:

const isMember = Boolean(Astro.locals.user?.isActive)

<Fragment set:html={renderMarkdown(isMember ? entry.body : entry.preview)} />

Logged-out visitors only get preview along with a gate banner linking to /login?next=..., while active members see the full body.

Handling this on the server beats a client-side blur for a few reasons:

  • View source can’t reveal member lessons.
  • You don’t need a separate JSON API for content.
  • SEO previews stay honest.

The tradeoff is that editing Markdown requires a rebuild and redeploy. That’s fine for a membership library you update weekly, though if you publish every hour you’ll want to move content into a CMS or Convex tables.

The built-in renderer stays intentionally tiny, covering headings, lists, fenced code, and links. If you need richer Markdown, plug in marked, remark, or Astro content collections.

Fig 1 · 1/4The server chooses what HTML to send
No session

Stage 8: Paddle Classic signed webhook

Payments live outside the login flow, with Paddle sending server-to-server events to a dedicated route.

Point your Classic webhook at:

https://members.your-domain.com/api/purchase

The handler parses form-encoded payloads, verifies p_signature, and routes by alert_name:

if (['payment_succeeded', 'payment_completed', 'checkout_completed'].includes(payload.alert_name)) {
  return activate(payload)
}

if (['payment_refunded', 'refund_issued', 'payment_dispute_created'].includes(payload.alert_name)) {
  return revoke(payload)
}

Signature verification rebuilds Paddle’s PHP-serialized payload and checks RSA-SHA1 with your public key. Invalid signatures return 403.

Activation checks the product ID before granting access:

if (!configuredProductId || productId !== configuredProductId) {
  return json(200, { ok: true, skipped: 'unknown_product' })
}

Then it upserts the member and checks paddleOrderId before recording the payment:

if (!payments.some((payment) => payment.paddleOrderId === orderId)) {
  await convex.mutation(anyApi.payments.recordPayment, { ... })
  await sendWelcomeEmail(email)
}

That duplicate guard matters because webhooks can repeat.

This is enough for sequential retries, but it isn’t a complete idempotency guarantee since two webhook requests could pass the lookup at the same time. Before handling meaningful payment volume, store webhook event IDs in a dedicated table and claim each ID inside a single mutation.

Refunds and disputes set isActive: false.

Watch out for one detail: this handler targets Paddle Classic, not Paddle Billing, which uses different payloads and verification. If your account is on Paddle Billing, swap src/lib/purchaseWebhook.ts.

The starter handles one product and one-time access well. It’s a poor fit for subscriptions with complex plan changes, tax invoicing inside your app, or marketplaces with split payouts.

Stage 9: Cloudflare Worker config

wrangler.jsonc deploys the compiled Astro Worker:

{
  "name": "astro-membership-starter",
  "main": "@astrojs/cloudflare/entrypoints/server",
  "compatibility_date": "2026-07-15",
  "compatibility_flags": ["nodejs_compat"],
  "vars": {
    "SITE_URL": "https://members.your-domain.com"
  },
  "assets": {
    "directory": "./dist",
    "binding": "ASSETS"
  }
}

nodejs_compat matters because Paddle signature verification uses Node’s crypto module.

Make sure SITE_URL matches your production origin, since both magic links and welcome emails depend on it.

Keep secrets out of wrangler.jsonc and push them with Wrangler:

npx wrangler secret put CONVEX_URL
npx wrangler secret put AUTH_SERVER_SECRET
npx wrangler secret put RESEND_API_KEY
npx wrangler secret put EMAIL_FROM
npx wrangler secret put PADDLE_PUBLIC_KEY
npx wrangler secret put PADDLE_PRODUCT_ID

Deploy with:

npm run build
npm run deploy

Add the custom domain in Cloudflare after the first deploy.

Stage 10: Environment setup

Local development needs Convex running:

npx convex dev

That connects to a development deployment and syncs your functions. Copy the CONVEX_URL it prints into .env.local.

Here are the minimum variables you need:

VariablePurpose
CONVEX_URLConvex deployment used by Astro
AUTH_SERVER_SECRETProtects server-only Convex functions
RESEND_API_KEYSends magic links and welcome mail
EMAIL_FROMVerified sender, e.g. members@your-domain.com
SITE_URLCanonical origin for email links
PADDLE_PUBLIC_KEYVerifies Classic webhook signatures
PADDLE_PRODUCT_IDLimits grants to your product
PUBLIC_PADDLE_CHECKOUT_URLOptional checkout button on /join

Keep .env.local out of Git and store production secrets in Wrangler.

If you want to create a member locally without going through Paddle, call users.upsertMember from the Convex dashboard:

{
  "email": "member@your-domain.com",
  "isActive": true,
  "serverSecret": "replace-with-a-long-random-value"
}

Once the user exists, head to /login and request a magic link.

Stage 11: Verification

I verify the starter in this order:

  1. Run npx convex dev and make sure it prints your deployment URL and the dashboard functions respond.
  2. Upsert a test user manually, request a magic link, and confirm the two-step verify flow creates a session.
  3. Open a guide while logged out and inspect the page source to verify only the preview is in the HTML. Then log in and make sure the full body appears.
  4. Log out, confirm the session row is deleted in Convex, and reopen the gated page to verify you’re back to the preview.
  5. Run Paddle’s webhook simulator with your public key configured. A bad signature should return 403, and a valid test payload should activate the member once.
  6. Send a refund alert from the simulator and make sure the member loses access on the next request.
  7. Deploy to production, open https://members.your-domain.com/login over HTTPS, and check that the cookies are marked Secure.

If magic links fail locally, check your Resend domain verification first. If webhooks fail in production, compare SITE_URL, your product ID, and the public key formatting with escaped newlines.

Tradeoffs and where this starter is a poor fit

What this starter is built for:

  • solo creators selling one library
  • Markdown-first content
  • passwordless login
  • Paddle Classic one-time purchases
  • low maintenance for a small team

Where I wouldn’t start from it:

  • A large free tier with a tiny paid upsell, because you still pay SSR costs on all your public pages.
  • Native mobile apps, which need token APIs while this starter relies on cookie sessions tied to a web domain.
  • Enterprise SSO, since you’ll end up replacing the magic-link flow entirely.
  • Complex subscriptions with plan upgrades, metered billing, and dunning, which belong in a billing integration layer this project doesn’t include.
  • Real-time collaboration. Convex can handle it, but the content model here is static Markdown files.

If you need a full learning platform, a community product, or a marketplace, you’ll outgrow this quickly.

A prompt to generate this site

You don’t need a zip file to start from this project. Create an empty folder, open it with your coding agent, and paste this prompt:

Build a generic paid membership site called "Member Library".

Use this stack:

- Astro with server-side rendering
- TypeScript in strict mode
- the Astro Cloudflare adapter
- Convex for users, sessions, magic links, and payments
- Resend for transactional email
- Paddle Classic for one-time payments
- local Markdown files for member content
- HTMX only for small form interactions

Keep the project small. Do not add React.

The site needs these pages:

- `/` with a short product introduction
- `/library` with guides and articles
- `/guides/[slug]` for guide pages
- `/articles/[slug]` for article pages
- `/login` for passwordless login
- `/join` for the Paddle checkout link
- `/thanks` after checkout

Create Astro API routes for:

- sending a Resend magic link
- confirming the magic link
- logging out
- receiving Paddle Classic webhooks

Use a flat Convex schema with separate tables for:

- users
- sessions
- magic links
- payments
- processed webhook events

Add indexes for every lookup path.

Every public Convex function must validate its arguments and return value.
Protect server-only Convex functions with `AUTH_SERVER_SECRET`.
Never expose this secret to browser code.

The login endpoint must return the same success response for known and unknown
emails. Add rate limits by email and IP address.

Magic links expire after 30 minutes and can only be used once. The first
email-link request must show a confirmation page without consuming the token.
Create the session only after the member confirms. Sessions expire after 30
days. Store the real session token in an HTTP-only, Secure, SameSite=Lax
cookie.

Accept an optional `next` path after login, but only allow a local path that
starts with one `/`. Reject protocol-relative URLs, backslashes, and different
origins to prevent open redirects.

Load the session in Astro middleware. Put the active member in
`Astro.locals.user`.

Each Markdown file must have:

- title
- description
- preview

Logged-out visitors can only receive the preview HTML. Render the complete
Markdown body on the server only after checking the active member. Do not send
member content in page data, client-side JavaScript, hidden HTML, or a public
JSON endpoint.

Verify every Paddle webhook signature before changing data. Check the configured
product ID. Claim each webhook event ID in one Convex mutation so retries and
concurrent deliveries cannot grant access twice. Activate access after a valid
payment. Revoke access after a refund or dispute.

Create `.env.example` with placeholders only. It must list:

- CONVEX_URL
- AUTH_SERVER_SECRET
- RESEND_API_KEY
- EMAIL_FROM
- EMAIL_REPLY_TO
- SITE_URL
- PADDLE_PUBLIC_KEY
- PADDLE_PRODUCT_ID
- PUBLIC_PADDLE_CHECKOUT_URL

Never create or print real credentials. Never read credentials from unrelated
projects or shell history. Keep `.env`, `.env.local`, build output, and local
deployment files out of Git. The [.env diff tool](/tools/env-diff/) compares
that example with a local `.env` and lists missing keys.

Add two short sample Markdown files. Add a README that explains local setup,
`npx convex dev`, Resend configuration, Paddle webhook configuration, testing,
and Cloudflare Workers deployment.

Run the TypeScript checks and production build. Fix every error before stopping.
Finish with a list of files created, tests run, and values I still need to
configure.

The prompt spells out the behavior and security boundaries, and it asks for two improvements beyond my first starter: rate limits on login emails and an atomic webhook-event claim.

You’ll still want to supervise the agent. Read through the generated webhook handler and access checks before connecting a real checkout.

How I would use this starter

If I were launching another paid library tomorrow, I’d start from this codebase because it’s generic on purpose, and customize it in a set order.

Start by renaming the product in src/lib/config.ts and replacing the sample guides in src/content/. Keep the preview field useful, focusing on the outcome readers will get instead of summarizing the middle lessons.

Next, wire up Resend with a dedicated subdomain like members@your-domain.com and warm that domain up before launch week. Once email works, connect your Paddle Classic checkout on /join, set the success URL to /thanks, point the webhook at /api/purchase, and test refund revocation before announcing the product.

From there, adjust the gating rules if you need to. Out of the box, access is binary and active members see everything. If you want a course-style drip, add publishedAt fields or move the content into Convex and query by entitlement.

When everything works locally, deploy to Cloudflare Workers and set SITE_URL to your real origin. Keep your marketing pages on a separate static site if SEO volume matters more to you than sharing auth cookies.

Leave the auth stack alone unless your requirements force a change, since the content workflow is usually where friction shows up. This setup fits a developer newsletter with a paid archive out of the box, whereas a team SaaS with roles and invoices needs a longer roadmap and should treat this as a reference implementation.

Want me to talk about your product? You can sponsor this site.

Related posts about astro: