Project 9: A SaaS Subscription Back End

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 9 min read · Updated

A plan changes only by webhook

  1. The client asks to subscribe. The server returns a checkout link and changes nothing.
  2. The provider takes the payment on its own page.
  3. The signed webhook arrives. A verified, first-time event activates the plan.
  4. Each limited feature checks the plan, and a past-due account is refused.

A SaaS product earns money from subscriptions, and behind every pricing page there is a back end that answers one question on every request: *what is this account allowed to do right now?* This project builds that core. It has plans with limits, a way to start a subscription, a webhook that activates the plan only when the provider confirms payment, and a limit check on the feature that is being sold. It combines the payment rules of lesson 37 with the access control of Project 3.

What you will build

  • GET /api/plans shows the plans and their limits.
  • POST /api/subscribe starts a checkout for a paid plan. It does not activate it.
  • POST /webhooks/billing receives signed events that activate, renew or mark an account past due.
  • GET /api/account shows the plan, its limits and the current usage.
  • POST /api/projects creates a project only if the plan allows more of them.

Design decisions before any code

There are three plans, free, pro and team, each with a price in cents and a limit for the number of projects. The prices in the code are only an example, and your own product will have its own. The account of each user has a plan, a status and a renewal date. The rule that makes billing safe is: the plan changes only because of a verified webhook, never because the client says so, and never because the browser came back from the payment page.

The limit check is called an entitlement check. It runs on the server on every request that uses a limited feature, and it reads the current plan from your own data. A front end can show a locked button to be polite, but the real lock is the check in the route.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken.
  3. Copy p-kit.js, p09-saas.js and p09.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest, then run node --test p09.test.js.

Read the webhook first: signature, duplicate check, then the state change. Then read the entitlement check in the projects route.

// Project 9: SaaS subscriptions. Plans, subscribe, limits per plan, and billing events from a provider webhook.
import express from 'express';
import crypto from 'node:crypto';
import { AppError, requireAuth, errorHandler, notFoundHandler } from './p-kit.js';

export const PLANS = {
  free: { priceCents: 0, projects: 1 },
  pro: { priceCents: 49900, projects: 10 },
  team: { priceCents: 199900, projects: 100 },
};

export const sign = (raw, secret) => crypto.createHmac('sha256', secret).update(raw).digest('hex');

export function createApp({ billing, webhookSecret, now = () => Date.now() }) {
  const app = express();
  const auth = requireAuth();
  const accounts = new Map();       // userId -> { plan, status, renewsAt }
  const projects = new Map();       // userId -> [names]
  const seen = new Set();

  const accountOf = (id) => accounts.get(id) ?? accounts.set(id, { plan: 'free', status: 'active', renewsAt: null }).get(id);

  // The webhook uses the raw body so the signature can be checked.
  app.post('/webhooks/billing', express.raw({ type: 'application/json' }), (req, res) => {
    const given = req.get('x-signature') ?? '';
    const expected = sign(req.body, webhookSecret);
    if (given.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected))) return res.status(400).json({ error: 'Bad signature' });
    const event = JSON.parse(req.body.toString('utf8'));
    if (seen.has(event.id)) return res.json({ duplicate: true });
    seen.add(event.id);

    const account = accountOf(event.userId);
    if (event.type === 'subscription.paid') Object.assign(account, { plan: event.plan, status: 'active', renewsAt: now() + 30 * 86_400_000 });
    if (event.type === 'subscription.payment_failed') account.status = 'past_due';
    if (event.type === 'subscription.cancelled') Object.assign(account, { plan: 'free', status: 'active', renewsAt: null });
    res.json({ received: true });
  });

  app.use(express.json());

  app.get('/api/plans', (req, res) => res.json(PLANS));

  // We do NOT activate the plan here. We start a checkout; the paid webhook activates it.
  app.post('/api/subscribe', auth, async (req, res) => {
    const plan = req.body?.plan;
    if (!PLANS[plan] || plan === 'free') throw new AppError('Choose pro or team', 422);
    const checkout = await billing.createCheckout({ userId: req.user.id, plan, amountCents: PLANS[plan].priceCents });
    res.status(201).json({ checkoutUrl: checkout.url });
  });

  app.get('/api/account', auth, (req, res) => res.json({ ...accountOf(req.user.id), limits: PLANS[accountOf(req.user.id).plan], used: (projects.get(req.user.id) ?? []).length }));

  // Entitlement check: what the plan allows is decided on the server, on every request.
  app.post('/api/projects', auth, (req, res) => {
    const account = accountOf(req.user.id);
    if (account.status === 'past_due') throw new AppError('Your last payment failed. Update your payment method.', 402);
    const list = projects.get(req.user.id) ?? [];
    if (list.length >= PLANS[account.plan].projects) throw new AppError(`Your ${account.plan} plan allows ${PLANS[account.plan].projects} project(s). Upgrade to add more.`, 403);
    projects.set(req.user.id, [...list, String(req.body?.name ?? 'Untitled')]);
    res.status(201).json({ count: list.length + 1 });
  });

  app.use(notFoundHandler, errorHandler);
  return app;
}

The test subscribes, shows that the plan is still free, sends a signed webhook, and then shows that the limit has risen. It also tests a duplicate event and a payment failure.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp, sign } from './p09-saas.js';
import { signToken } from './p-kit.js';

const SECRET = 'whsec_saas';
const as = (id) => ({ Authorization: `Bearer ${signToken({ id, role: 'user', name: `u${id}` })}` });
const hook = (app, event) => {
  const raw = JSON.stringify(event);
  return request(app).post('/webhooks/billing').set('Content-Type', 'application/json').set('x-signature', sign(raw, SECRET)).send(raw);
};

test('project 9: limits follow the plan and the webhook', async () => {
  const app = createApp({ billing: { createCheckout: async ({ plan }) => ({ url: `https://pay.example/${plan}` }) }, webhookSecret: SECRET });

  assert.equal((await request(app).post('/api/projects').set(as(1)).send({ name: 'A' })).status, 201);
  assert.equal((await request(app).post('/api/projects').set(as(1)).send({ name: 'B' })).status, 403);       // free plan: 1 project

  assert.equal((await request(app).post('/api/subscribe').set(as(1)).send({ plan: 'free' })).status, 422);
  const checkout = await request(app).post('/api/subscribe').set(as(1)).send({ plan: 'pro' });
  assert.equal(checkout.body.checkoutUrl, 'https://pay.example/pro');
  assert.equal((await request(app).get('/api/account').set(as(1))).body.plan, 'free');                       // not active until paid

  assert.equal((await request(app).post('/webhooks/billing').set('Content-Type', 'application/json').set('x-signature', 'bad').send('{}')).status, 400);
  await hook(app, { id: 'e1', type: 'subscription.paid', userId: 1, plan: 'pro' });
  assert.equal((await request(app).get('/api/account').set(as(1))).body.plan, 'pro');
  assert.equal((await request(app).post('/api/projects').set(as(1)).send({ name: 'B' })).status, 201);

  assert.equal((await hook(app, { id: 'e1', type: 'subscription.paid', userId: 1, plan: 'team' })).body.duplicate, true);   // same event again
  assert.equal((await request(app).get('/api/account').set(as(1))).body.plan, 'pro');

  await hook(app, { id: 'e2', type: 'subscription.payment_failed', userId: 1 });
  assert.equal((await request(app).post('/api/projects').set(as(1)).send({ name: 'C' })).status, 402);

  await hook(app, { id: 'e3', type: 'subscription.cancelled', userId: 1 });
  assert.equal((await request(app).get('/api/account').set(as(1))).body.plan, 'free');
});

Rules worth understanding

Subscribe starts, the webhook finishes. /api/subscribe asks the billing provider for a checkout link and returns it. The account stays on its old plan. Only a verified subscription.paid event changes the plan, and the test proves that the plan does not change before the webhook.

Signed and raw. The webhook route is registered before express.json() and uses the raw body for the HMAC check, as in lesson 37, with a constant-time comparison.

Idempotent events. The id of every event is remembered, and a repeated event is acknowledged without being applied twice. A renewal that was counted twice would extend an account for free.

Past due. When a payment fails, the status becomes past_due, and the projects route answers 402 with a clear message. You decide the policy: many products give a grace period before they limit a feature.

Limits on every request. The number of projects is compared with the limit of the current plan at the moment of creation. A free account that tries to create a second project gets 403, and the same request works after the paid webhook. A downgrade or a failed payment takes effect immediately.

Security and honesty notes

Never trust a plan name from the client in the webhook either. The provider event should contain an id that you created during checkout, which you map back to your own record. Prices, taxes and invoices follow the laws of your country, and a real provider handles much of that for you. This project is a learning model, not an accounting system.

A real provider has its own library, event names and signature header, so follow its current documentation. This lesson uses a fake provider, so that the logic can be run and tested.

Extend it

Your task

  1. Add a team seat limit and an invite route that respects it.
  2. Add a yearly plan with a renewal date, and a job from lesson 35 that reminds people before renewal.
  3. Add a customer portal route for cancellation that takes effect at the end of the period.

How to check it worked

  • Subscribing does not change the plan by itself.
  • A repeated webhook is applied once.
  • A past-due account is refused with 402 on limited features.

On your resume. "Built a subscription back end with plan limits, signed idempotent billing webhooks and past-due handling" is concise and shows that you understand what a paid product needs. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

What is an entitlement check?

A server-side check, on every request, that the account's current plan allows the feature or the amount that the request needs.

Why not activate the plan when the user returns from checkout?

Anyone can open the return URL. Only a signed message from the provider proves that money moved.

What is past due?

The state of an account whose latest payment failed. Products usually limit features, with or without a grace period, until it is fixed.

Practise with interview questions