Check Stripe access in your own app
A customer paid. Does your app know?
A customer who just paid can still be on free in your app, and one whose subscription ended can still have pro. Nobody tells you until the customer does, or never.
Fravni emails you when a payment doesn’t give a customer access in your app, or a cancellation doesn’t remove it. Stripe sends Fravni its own copy of each one. Fravni asks your app for that customer’s plan and compares. Your handler keeps its job, and Fravni only reads.
This guide has copy-ready code for Next.js, Express and FastAPI. On another framework, a prompt for your AI coding tool asks for the same route. Your app needs each customer’s Stripe customer ID on their record. A column on your user table is enough. You add one read-only route, then build two monitors, each from a recipe: a ready-made monitor you fill in. If you sell upgrades, you add a third kind.
Before you start, have:
- a Stripe Administrator or Developer role, to add a webhook;
- the right to deploy your app and set its environment variables;
- a way to add a file to your app, or a DNS record on its domain;
- each Stripe price you sell, and the plan name your app stores for it.
Keep plans in Airtable instead? Follow Check Stripe plans in Airtable.
Your webhook handler can tell Stripe “received” and still leave a paying customer on free
Section titled “Your webhook handler can tell Stripe “received” and still leave a paying customer on free”Stripe’s webhook guide asks your handler to reply “received” first. Stripe then counts the event delivered, even if saving the plan fails after. Your error tracker stays quiet too: a skipped update or a wrong plan name throws nothing.
Example data
| Check detail | Example |
|---|---|
| What came in | Stripe invoice.paid |
| Customer found by | Stripe customer ID = cus_R4kq9Lm2 |
| Expected Plan | pro |
| Observed Plan | free |
| Read at | 12:05 UTC |
| Deadline | 12:05 UTC |
| Result | Not matched by deadline |
Add one read-only route that looks up a customer’s plan in your database
Section titled “Add one read-only route that looks up a customer’s plan in your database”Pick your framework. Each tab shows the two files to add.
For the App Router, Next.js 15 or later.
Add two files. The first is your lookup, at lib/access.ts (under src/ if your project uses
it). Replace its body with a query against
your own database. It returns the customer’s record, or null when your app has none.
export type Access = { stripeCustomerId: string; // as stored on your record, never taken from the request plan: string; // the plan name your app stores, such as "pro" active: boolean; // true while the customer has paid access};
export async function findAccess(stripeCustomerId: string): Promise<Access | null> { // Replace with your query. Return null when your app has no such customer. // Use an exact-match, parameterised query on the stored Stripe customer ID. throw new Error(`findAccess is not written yet: ${stripeCustomerId}`);}The second is the route. Copy it as it is to app/api/access/[customerId]/route.ts, also under
src/ if your project uses it. If your project has no @/ import alias, import the lookup by its relative path instead.
import { createHash, timingSafeEqual } from "node:crypto";import { findAccess } from "@/lib/access";
// Hashing both sides gives equal lengths, so timingSafeEqual never throws or leaks a length.function digest(value: string): Buffer { return createHash("sha256").update(value).digest();}
const noStore = { "Cache-Control": "no-store" };
export async function GET( request: Request, { params }: { params: Promise<{ customerId: string }> },) { const token = process.env.ACCESS_CHECK_TOKEN; if (!token) { console.error("ACCESS_CHECK_TOKEN is not set"); return new Response(null, { status: 500, headers: noStore }); } const header = request.headers.get("authorization") ?? ""; if (!timingSafeEqual(digest(header), digest(`Bearer ${token}`))) { return new Response(null, { status: 401, headers: noStore }); } const { customerId } = await params; const access = await findAccess(customerId); if (!access) { return new Response(null, { status: 404, headers: noStore }); } return Response.json( { id: access.stripeCustomerId, plan: { entitlement: access.plan }, active: access.active }, { headers: noStore }, );}The route needs Next.js’s default Node.js runtime, so don’t set runtime to edge.
For Express 5.
Add two files beside the file that creates your app. The first is your lookup, access.cjs.
Replace its body with a query against your own database. It returns the customer’s record, or
null when your app has none.
// Resolves to { stripeCustomerId, plan, active }, or null:// stripeCustomerId: as stored on your record, never taken from the request// plan: the plan name your app stores, such as "pro"// active: true while the customer has paid accessasync function findAccess(stripeCustomerId) { // Replace with your query. Return null when your app has no such customer. // Use an exact-match, parameterised query on the stored Stripe customer ID. // In an ES-module app, load your database code with `await import(...)`. throw new Error(`findAccess is not written yet: ${stripeCustomerId}`);}
module.exports = { findAccess };The second is the route, access-route.cjs. Copy it as it is.
const { createHash, timingSafeEqual } = require("node:crypto");const path = require("node:path");const express = require("express");const { findAccess } = require("./access.cjs");
// Hashing both sides gives equal lengths, so timingSafeEqual never throws or leaks a length.function digest(value) { return createHash("sha256").update(value).digest();}
const router = express.Router();
// Serves your proof files from public/ beside this file, whatever folder the app starts in.// Until the folder exists, these paths answer 404.router.use( "/.well-known/fravni-connection", express.static(path.join(__dirname, "public", ".well-known", "fravni-connection")),);
router.get("/api/access/:customerId", async (req, res) => { res.set("Cache-Control", "no-store"); const token = process.env.ACCESS_CHECK_TOKEN; if (!token) { console.error("ACCESS_CHECK_TOKEN is not set"); return res.status(500).end(); } const header = req.get("authorization") ?? ""; if (!timingSafeEqual(digest(header), digest(`Bearer ${token}`))) { return res.status(401).end(); } // A failed lookup answers 500 with no body, so no error page shows your database's error. let access; try { access = await findAccess(req.params.customerId); } catch (err) { console.error(err); return res.status(500).end(); } if (!access) { return res.status(404).end(); } res.json({ id: access.stripeCustomerId, plan: { entitlement: access.plan }, active: access.active });});
module.exports = router;Then, in the file that creates your app, add the route before any login check:
const accessRouter = require("./access-route.cjs");app.use(accessRouter);If your app uses ES modules, write import accessRouter from "./access-route.cjs"; instead of
the require line. The .cjs ending lets both files work in either kind of app.
The route file also serves your proof folder: the proof file you add there later shows
Fravni the host is yours. Keep public/ beside these files. Until you add a
proof file, the folder can be missing, and your app still starts.
For FastAPI 0.141 or later.
Add two files beside the file that creates your app. The first is your lookup, access.py.
Replace its body with a query against your own database. It returns the customer’s record, or
None when your app has none.
from typing import TypedDict
class Access(TypedDict): stripe_customer_id: str # as stored on your record, never taken from the request plan: str # the plan name your app stores, such as "pro" active: bool # True while the customer has paid access
def find_access(stripe_customer_id: str) -> Access | None: # Replace with your query. Return None when your app has no such customer. # Use an exact-match, parameterised query on the stored Stripe customer ID. raise NotImplementedError(f"find_access is not written yet: {stripe_customer_id}")The second is the route, access_route.py. Copy it as it is. It stays out of your app’s API
docs.
import hashlibimport hmacimport loggingimport osfrom pathlib import Path
from access import find_accessfrom fastapi import APIRouter, FastAPI, Request, Responsefrom fastapi.responses import JSONResponsefrom fastapi.staticfiles import StaticFiles
logger = logging.getLogger(__name__)
# Your proof files go in public/ beside this file, whatever folder the app starts in.PROOF_DIR = Path(__file__).parent / "public" / ".well-known" / "fravni-connection"
NO_STORE = {"Cache-Control": "no-store"}
router = APIRouter()
# Hashing both sides gives equal lengths, so compare_digest never leaks a length.# It compares bytes: compare_digest refuses a str holding non-ASCII characters.def digest(value: str) -> bytes: return hashlib.sha256(value.encode()).digest()
@router.get("/api/access/{customer_id}", include_in_schema=False)def get_access(customer_id: str, request: Request) -> Response: token = os.environ.get("ACCESS_CHECK_TOKEN") if not token: logger.error("ACCESS_CHECK_TOKEN is not set") return Response(status_code=500, headers=NO_STORE) header = request.headers.get("authorization", "") if not hmac.compare_digest(digest(header), digest(f"Bearer {token}")): return Response(status_code=401, headers=NO_STORE) access = find_access(customer_id) if access is None: return Response(status_code=404, headers=NO_STORE) return JSONResponse( { "id": access["stripe_customer_id"], "plan": {"entitlement": access["plan"]}, "active": access["active"], }, headers=NO_STORE, )
def add_access_route(app: FastAPI) -> None: app.include_router(router) # StaticFiles refuses a missing folder, so the proof folder is mounted only once it # exists. Until you add a proof file and deploy, its paths answer 404. if PROOF_DIR.is_dir(): app.mount("/.well-known/fravni-connection", StaticFiles(directory=PROOF_DIR))Then, in the file that creates your app, add the route:
from access_route import add_access_route
add_access_route(app)If your app is a package, with imports like from .models import User or
from app.models import User, put a dot before both new module names: from .access_route
here, and from .access in access_route.py.
The route file also serves your proof folder: the proof file you add there later shows
Fravni the host is yours. Keep public/ beside these files. Until you add a
proof file, the folder can be missing, and your app still starts.
The route returns data only to a GET with your secret token, and only three fields. For the
example customer it answers:
{ "id": "cus_R4kq9Lm2", "plan": { "entitlement": "pro" }, "active": true}id must be the Stripe customer ID stored on your record, never the one in the web address. It is
how Fravni knows it read the right customer. For a customer who exists but has no
paid access, return active: false, not null.
After each payment, Fravni reads your route until it matches or the deadline passes: three reads with the default timing. If none got an answer, it tries once more, late.
Another framework, or want your AI coding tool to write the route? Paste this prompt into it. It asks for the whole route, the proof folder and tests. You still add the proof file in the token steps below. Read what the tool writes. Then run a live test read before you switch the monitor on: it shows what your route answered.
Add a read-only route to this app for Fravni access checks. Use this app's framework and database access.
Route- GET /api/access/{customerId}. Answer GET only.- Match that path exactly, with no trailing-slash redirect.- Keep the route and the proof folder out of any login check or redirect.- Send Cache-Control: no-store on every answer.
Token- Read the token from the ACCESS_CHECK_TOKEN environment variable.- If it is unset or empty, log an error and answer 500 with no body.- Answer 401 with no body unless the Authorization header equals "Bearer " followed by the token.- Compare in constant time, even when lengths differ, so the comparison can't leak the token.
Answer- Find the customer whose stored Stripe customer ID exactly equals customerId. Use a parameterised query.- If there is none, answer 404 with no body.- Otherwise answer 200 with JSON, as application/json, holding exactly these fields: {"id": "<the Stripe customer ID stored on the record>", "plan": {"entitlement": "<the plan name this app stores>"}, "active": <true while the customer has paid access, else false>}- Take id from the record, never from the URL.- A customer who exists but has no paid access gets "active": false, not a 404.
Proof folder- Serve each file in public/.well-known/fravni-connection/ at /.well-known/fravni-connection/<file name>, exactly as stored.- A missing folder must not stop the app or make other requests fail. Until it exists, those paths answer 404.
Tests- Write a test for each case above.
When you finish, list the plan names this app stores, one per line.Add a Stripe webhook that still fires when your own handler fails
Section titled “Add a Stripe webhook that still fires when your own handler fails”This webhook sends Fravni its own copy of each payment and cancellation. So a check starts even if your own handler never runs. Adding it changes no charge, customer or other webhook. Fravni only receives events, and asks for no Stripe key.
- In Fravni, start a monitor from the recipe “Stripe payment gives access to the plan it buys, one plan per invoice”.
- When you choose where its events come from, pick Stripe and create a new webhook. Copy the webhook address it gives you.
- In your live Stripe account, open Workbench from the Developers menu, or press ~. Open its Webhooks tab and create a destination: Stripe’s word for a webhook. Choose events from Your account.
- For the payload format, choose Snapshot, not Thin, even though Stripe suggests Thin. A thin event carries only an ID, so Fravni would have no plan to read.
- Stripe shapes each event to the API version you pick here, and Fravni reads
only the versions it knows. Choose the newest API version ending in
.endive. You can’t change it later: a wrong pick means a new webhook, then deleting the old one. - Select the event types
invoice.paidandcustomer.subscription.deleted. Picked now, your other monitors need nothing more in Stripe. - Choose Webhook endpoint, paste the address from step 2 as the Endpoint URL, and create the destination.
- Reveal the signing secret, which starts
whsec_, and paste it into your monitor. It proves each event came from Stripe. If it is pasted wrong, Stripe’s deliveries are refused, and you get an email.
Set the webhook up in live mode: a sandbox webhook never sees your live payments. From each event, Fravni keeps only the fields it takes and a scrambled code to spot repeats, never the whole event.
Only requests with your secret token get an answer, and only a host you prove with a file or DNS record gets read
Section titled “Only requests with your secret token get an answer, and only a host you prove with a file or DNS record gets read”-
Make a long random token, for example with
openssl rand -hex 32. Set it asACCESS_CHECK_TOKENin your app’s environment, then deploy. Without it, the route answers every request with an error and never with data. -
On your monitor’s page, open Connection › Settings and select Create connection. Choose your app’s exact host, such as
app.example.com, and paste the token as its credential. Fravni sends it asAuthorization: Bearerand the token, encrypts it, and never returns or logs it. Never put the token in the path or a sample. -
If your app sends signed-out visitors to a login page, or refuses them, leave
/api/access/and/.well-known/fravni-connection/out of that check, and deploy. In Next.js, that check is yourproxy.tsmatcher (middleware.tsbefore Next.js 16). The proof and the reads carry no login and follow no redirect. -
Prove the host is yours. The connection shows a proof token and a DNS record name. Do one of these, then verify the proof from the connection:
- In
public/.well-known/fravni-connection/, add a file named with the proof token. Its only content is the proof token. Deploy. - Add a TXT record with the name shown and the proof token as its value.
If the proof fails just after a deploy, wait a minute and verify again.
- In
A proof covers that exact host only: example.com proves nothing for app.example.com.
Fravni reads no host until its owner proves it. It sends only GET, over HTTPS,
and keeps only the values it checks, never the rest of the answer.
Map each Stripe price to a plan name, and get an email when a payment doesn’t grant it
Section titled “Map each Stripe price to a plan name, and get an email when a payment doesn’t grant it”On your monitor’s page, open Connection › Request and set the path to
/api/access/{customer_id}. Type it exactly: Fravni fills {customer_id}
with each event’s Stripe customer ID. Don’t end the path with /: your app could redirect, and
the read would fail. The one exception: if your next.config sets trailingSlash: true, end it
with /.
On Connection › Expected values, the recipe has three expected values: values your route’s
answer must hold, each compared with what Stripe says. A Field path is the path to that value. Set the
field path of the one with Proves it’s the right record ticked, which tells Fravni the answer belongs to the customer,
to id. Set the plan’s field path to plan.entitlement and the access’s to active.
Each Stripe price has a price ID that starts price_. Open Event source › Fields, and under
Translated fields add one pair per price you sell: From its price ID, To the plan name exactly as your app stores it. To
find a price ID, open Workbench’s Events tab and filter by invoice.paid. Open a recent payment
on that plan. The price ID sits under the invoice line’s pricing, in price_details, as the
price value.
Fravni never guesses a plan. A payment at a price with no pair gets no check. You get one email, and the monitor shows as suspended until the next payment at a mapped price. Suspended means some payments couldn’t be checked; the monitor still checks payments at mapped prices.
The deadline is how long Fravni waits for your route to match. It runs from the moment Stripe’s event reaches Fravni, and the recipe uses the default deadline. Fravni reads again until the route matches or the deadline passes, so a slow handler isn’t flagged early. In the monitor’s timing settings, set the deadline after your handler usually finishes. See read-timing questions.
This works when each invoice buys one plan. An upgrade invoice can list the old price first, so a right plan can read as wrong. The payment monitor then opens an issue and you get an email, though your app is right: confirm the plan in Stripe, then resolve the issue. If you sell upgrades, use one monitor per price instead of this one.
Get an email when a customer still has paid access after their subscription ends
Section titled “Get an email when a customer still has paid access after their subscription ends”Start a second monitor from the recipe “Stripe subscription deleted revokes access”. When you choose where its events come from, pick the webhook your payment monitor uses. Nothing changes in Stripe.
Choose the connection to your app for this monitor, then set the same path on
Connection › Request. On Connection › Expected values, set the Field path of the one with
Proves it’s the right record ticked to id, and the access one’s to active: the recipe expects false. It doesn’t copy them over from the payment monitor. Set the
deadline as for the payment monitor.
Stripe sends this event when the subscription actually ends, not when the customer clicks cancel.
So access kept until the end of the paid period isn’t flagged. This works when each customer has
one subscription. If your app deletes the user when a subscription ends, the route answers that it
has none, and the check reads Not found by deadline. Keep the record with active: false
instead.
Selling upgrades? Add one monitor per price, so a paid upgrade is checked for its new plan
Section titled “Selling upgrades? Add one monitor per price, so a paid upgrade is checked for its new plan”Skip this section if you don’t sell upgrades. This monitor checks every paid invoice that includes one price, wherever that price sits on the invoice. Start it from the recipe “Stripe payment for a plan you pick gives access, upgrades included”, and pick the price. Choose the webhook and connection your payment monitor uses, then set the same path on Connection › Request.
On Connection › Expected values, its recipe has two expected values. Set the Field path of the one
with Proves it’s the right record ticked to id. Set the other’s to plan.entitlement, choose
Fixed value, and type the plan that price buys, exactly as your app stores it.
Add one such monitor per paid price, and keep the cancellation monitor. With three paid prices, you run four monitors: one per price, plus the cancellation monitor. Once they are live, deactivate the payment monitor. If your plan’s limit stops one going live, deactivate the payment monitor first. Its webhook and connection keep serving your other monitors, and an inactive monitor doesn’t count toward your plan’s monitor limit. A new price then needs its own monitor. See upgrades and prorations.
A downgrade brings no paid invoice, so no monitor here checks it. An upgrade within the same
billing period is checked only when Stripe invoices it at once, which needs
proration_behavior: always_invoice; Stripe’s default bills it at the next renewal. A switch to a
different billing period, such as monthly to yearly, is invoiced at once. An upgrade monitor’s sample needs a payment that includes its price: see
testing.
Tell a wrong plan from an app that didn’t answer
Section titled “Tell a wrong plan from an app that didn’t answer”Fravni reads your route until it matches or the deadline passes. What your route answers decides the result:
| Your route answers | Result | What to do |
|---|---|---|
| The expected plan and access | Match observed at the read time | Nothing |
| Another plan or access | Not matched by deadline, with both values | Fix the customer’s access, then recheck |
No such customer (404) |
Not found by deadline | Check the customer is in your database. If every customer reads this, check the path and that the route is deployed |
A refused token (401 or 403) |
Could not check, with the cause | Match the connection’s token to ACCESS_CHECK_TOKEN. If they match, keep your login check off the route |
| An error, or no answer in time | Could not check, with the cause | Fix your app |
| A redirect | Could not check, with the cause | Check the path matches your route exactly, and that your login check skips it |
A missing customer or a wrong plan opens an issue for that payment, and you get an email. Could not check opens one issue for the connection or the monitor, not one per payment, and never counts as a match.
A check starts only when Stripe’s copy of a payment or an ended subscription arrives. An event Stripe never delivers can’t be checked. If you bill through Stripe Accounts v2, some events may leave out the Stripe customer ID. These monitors can’t check those, and you get an email.
Test each monitor on a real customer before you switch it on, no live payment needed
Section titled “Test each monitor on a real customer before you switch it on, no live payment needed”Testing is optional, but recommended. Each test needs a sample: one Stripe event for a customer your app knows. Take the events from a Stripe sandbox, then put a real customer’s ID in them:
- Open Sandboxes from the Dashboard’s account picker and create one. At its API version step,
choose the newest version ending in
.endive. - Add a product with a price.
- Create a subscription at that price, and pay with test card
4242 4242 4242 4242. - In Subscriptions, open ⋯ on it, choose Cancel subscription and cancel immediately.
- From the sandbox’s Events tab, copy the full payload of the
invoice.paidevent and of thecustomer.subscription.deletedevent. - In each copy, replace the
customervalue directly underdata.objectwith a real customer’s Stripe customer ID from your app. Pick a paying customer for the payment sample, and one whose subscription has ended for the cancellation sample. The test doesn’t check Stripe’s signature, so the edited event works. Testing only reads your route: it sends nothing to that customer and changes nothing in Stripe or your app. - In the payment sample’s invoice line, under
pricing, inprice_details, replace thepricevalue with the live price ID that customer pays, one already in your payment monitor’s map. For an upgrade monitor, copy the payment sample again and use the price that monitor checks.
Test each monitor in two parts. Paste its event as the sample and run it: Fravni shows the fields it took and the request it will send to your app. Then run a live test read: it shows what your route answered, and the result. Testing uses none of your checks.
Publishing reads nothing, so the live test read is your one look at your route’s answer before the monitor starts. If the monitor can’t find its customer, its first check ends Not found by deadline: Fravni opens an issue, and emails the account owner if your alert settings and sending limits allow.
Fix the access, then recheck the customer: rechecks are free
Section titled “Fix the access, then recheck the customer: rechecks are free”The account owner can receive an email about each new issue. It shows the Stripe customer ID, the value expected and the value found. Open the issue in Fravni. If your app is wrong, fix the customer’s access or your handler, then recheck the customer. A recheck reads your route once, now. A match reads Matched later at the read time, beside the original deadline result.
Sometimes your app is right and the check is wrong: after an upgrade invoice, or a payment just after a cancellation. A recheck can’t clear these, because the check keeps the value it first expected. Confirm the plan in Stripe, then resolve the issue.
Whether an email goes out depends on your alert settings and sending limits. A match shows the access your route returned at the read time. It does not prove this payment or cancellation set it.
Start with your Stripe payments, free
Section titled “Start with your Stripe payments, free”The Free plan is permanent. Each monitor, upgrade monitors included, counts toward your plan’s monitor limit: see pricing and plan limits.
For why access checks matter, see paid access. Keep plans in Airtable? See Check Stripe plans in Airtable.
© 2026 Fravniden
Airtable and the Airtable trademark are registered trademarks of Formagrid Inc dba Airtable. Cloudflare is a registered trademark of Cloudflare, Inc. Other product names are trademarks of their owners. Fravni is independent of HubSpot, Inc. and every other company named on this site, and is not authorized, endorsed or sponsored by, or affiliated with, any of them.
Vercel, the Vercel design, Next.js and related marks, designs and logos are trademarks or registered trademarks of Vercel, Inc. or its affiliates in the US and other countries.