Skip to main content
Tutorials

Cancel a subscription without cutting access too early (Stripe cancel_at_period_end and Polar canceled vs revoked)

A user who cancels keeps what they paid for until the period ends. How to handle cancel_at_period_end in Stripe and canceled vs revoked in Polar.

Israel Palma Sebastià

This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included

A user pays for the monthly plan on the 3rd. On the 10th they decide they won't renew and click "Cancel subscription". On the 11th they log into your app and find themselves on the free plan, locked out of what they'd paid for until the 3rd of next month.

It's one of the most common bugs in small SaaS apps, and it almost always starts in the same place: the webhook handler sees the word cancel in the event name and sets the plan to FREE. In this post we look at what Stripe and Polar actually send when someone cancels, what to store in the database, and how to write the access check so the cutoff date is the one the user paid for.

Canceling and ending are two different moments

In almost any SaaS, when a user cancels from the customer portal, two separate things happen at different times:

  1. Today: the subscription is flagged not to renew. It's still active and the user keeps what they paid for.
  2. At the end of the period: the subscription ends. Now access goes away.

In between, the user can change their mind and reactivate, and you have to handle that too. If your code only reacts to the first moment, you cut access weeks early. If it only reacts to the second but misreads the status, you leave access on forever.

What Stripe sends

In Stripe, canceling at period end means setting cancel_at_period_end: true on the subscription. According to the docs, this lets the subscription run through the time the customer already paid for, and it can be reverted by setting the field back to false any time before the period ends.

These are the events:

Event When it arrives What it means
customer.subscription.updated When the cancellation is scheduled (and when it's undone) cancel_at_period_end changes; status stays active
customer.subscription.deleted When the period ends, or on immediate cancellation Status canceled; it can no longer be reactivated

There's a third path worth knowing: cancel_at, a specific cancellation date that doesn't have to match the end of the period (if the date falls earlier, Stripe adjusts the item's current_period_end to that date). If you ever let users cancel on a specific date, or use subscription schedules with end_behavior: cancel, the cutoff information comes through there, not through cancel_at_period_end.

And one detail from the recent API: since version 2025-03-31.basil, current_period_end lives on each subscription item (subscription.items.data[0].current_period_end) and no longer on the subscription itself.

What Polar sends

Polar has a dedicated event for each moment, and that's where the trap is. Its docs explain it in the cancellations section:

  • subscription.canceled: the user has canceled. The subscription is still active, but with cancel_at_period_end set to true.
  • subscription.uncanceled: they've undone the cancellation.
  • subscription.revoked: the subscription is permanently revoked, billing stops and benefits are removed.

With those names, it feels natural to write this:

// ❌ Cuts access the day the user cancels
case 'subscription.canceled':
case 'subscription.revoked':
  await db.subscription.update({
    where: { subscriptionId: event.data.id },
    data: { status: 'CANCELED' },
  });
  break;

And it's wrong. As far as access is concerned, subscription.canceled is just another update: store cancelAtPeriodEnd: true and leave the status as it comes. Only subscription.revoked closes the door. Polar also sends subscription.updated for all of these changes (its docs describe it as the catch-all event for cancellations and reactivations), so handling all of them with the same sync function is the safest option.

One more warning if you use the Polar SDK. validateEvent runs the payload through its schemas and gives it back in camelCase, with dates as Date: the field is event.data.cancelAtPeriodEnd, not cancel_at_period_end. If you read the snake_case names from the JSON examples, everything comes through as undefined, and the usual || false turns that into "never cancels".

What to store in the database

To decide access you need three pieces of data per subscription. Here's a minimal Prisma model:

model Subscription {
  id                String   @id @default(cuid())
  userId            String
  provider          String   // 'STRIPE' | 'POLAR'
  subscriptionId    String
  status            String   // active, trialing, past_due, canceled...
  currentPeriodEnd  DateTime
  cancelAtPeriodEnd Boolean  @default(false)
  canceledAt        DateTime?
  updatedAt         DateTime @updatedAt

  @@unique([provider, subscriptionId])
  @@index([userId])
}

The important part is that the webhook copies the provider's state instead of translating events into decisions. One sync function for every subscription event:

// Polar: fields arrive in camelCase after validateEvent
async function syncPolarSubscription(sub: {
  id: string;
  status: string;
  currentPeriodEnd: Date;
  cancelAtPeriodEnd: boolean;
  canceledAt: Date | null;
  metadata: Record;
}) {
  const userId = String(sub.metadata.userId ?? '');
  if (!userId) return;

  const data = {
    status: sub.status,
    currentPeriodEnd: sub.currentPeriodEnd,
    cancelAtPeriodEnd: sub.cancelAtPeriodEnd,
    canceledAt: sub.canceledAt,
  };

  await db.subscription.upsert({
    where: { provider_subscriptionId: { provider: 'POLAR', subscriptionId: sub.id } },
    update: data,
    create: { userId, provider: 'POLAR', subscriptionId: sub.id, ...data },
  });
}

switch (event.type) {
  case 'subscription.created':
  case 'subscription.updated':
  case 'subscription.active':
  case 'subscription.canceled':
  case 'subscription.uncanceled':
  case 'subscription.revoked':
    await syncPolarSubscription(event.data);
    break;
}

subscription.revoked goes through the same function: the payload already carries the final status, and storing it is all there is to do. The userId comes from the metadata you set when creating the checkout; if you resolve it through the Polar customer instead, change that line.

Stripe works the same way, with one difference: since event order isn't guaranteed, it pays to fetch the subscription with stripe.subscriptions.retrieve() before storing it, as we explain in Stripe webhooks in Next.js 16.

The access check

With that data, "does this user have access?" is answered without looking at which event came last:

const ACCESS_STATUSES = new Set(['active', 'trialing']);

export function hasActiveAccess(sub: {
  status: string;
  currentPeriodEnd: Date;
} | null): boolean {
  if (!sub) return false;
  if (!ACCESS_STATUSES.has(sub.status)) return false;
  return sub.currentPeriodEnd.getTime() > Date.now();
}

cancelAtPeriodEnd isn't part of the check, on purpose. A canceled subscription that's still within its period stays active with a future currentPeriodEnd, so it has access. When the period ends, the provider sends the final event, the status becomes canceled and access closes.

The currentPeriodEnd condition is a safety belt in case the last webhook never arrives (a deploy that's down that day, a disabled endpoint). With it, the worst case is granting access until the date the user paid for, not forever. If you'd rather add a few hours of grace to absorb provider delays on renewal, add them here, not in the webhook.

past_due (the renewal charge failed) is a product decision. Stripe keeps retrying the charge according to your settings and, after the number of failed attempts you configure in the dashboard, it either cancels the subscription or marks it unpaid, depending on what you choose there. Some SaaS apps keep access during that window and others cut it; what matters is that the decision lives in hasActiveAccess and nowhere else.

This function runs on the server, in the same place you check the session: in the page, the server action or the route handler that serves the paid feature. On the client, the plan is only for rendering the UI.

What the user sees

With cancelAtPeriodEnd and currentPeriodEnd stored, the billing page can tell the truth:

{sub.cancelAtPeriodEnd
  ? `Your plan ends on ${formatDate(sub.currentPeriodEnd)}`
  : `Renews on ${formatDate(sub.currentPeriodEnd)}`}

And it's worth offering a reactivate button until the period is over. In Stripe that's stripe.subscriptions.update(id, { cancel_at_period_end: false }); in Polar, the customer portal allows it and you get subscription.uncanceled. A user who cancels by mistake on a Tuesday and undoes it on Thursday shouldn't have to go through checkout again.

How to test it

Testing the end of a period without waiting a month takes some tooling:

  • Stripe: test clocks let you create a subscription in the test environment and fast-forward the clock past current_period_end. That's how you see customer.subscription.deleted arrive locally.
  • Polar: in the sandbox, cancel from the customer portal and check that subscription.canceled arrives and the user still has access. For the end, you can revoke the subscription from the dashboard and check that subscription.revoked arrives.

In both cases, the test that catches the most bugs is the first one: cancel, and verify the user is still in the next day.

Takeaways

  • Canceling schedules the end; access is cut when the provider says the subscription is over.
  • In Polar, treat subscription.canceled as an update. Only subscription.revoked closes access.
  • Store status, currentPeriodEnd and cancelAtPeriodEnd, and let a single function decide access.
  • With the Polar SDK, fields arrive in camelCase.

If you're setting up payments from scratch, the base integration is in how to integrate Polar in Next.js, and the case for one provider or the other in Polar vs Stripe for an indie SaaS. CREA.MBA ships both providers behind the same interface, with a subscription model that has these fields in the Prisma schema.

Does your app cut access when the user cancels or when the period ends? Have you checked it with a test subscription?

Next.jsPrismaStripePaymentsPolar

Enjoyed this article?

Subscribe for more tutorials and tips on building products with AI