惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
A
About on SuperTechFans
博客园 - Franky
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
B
Blog
Microsoft Security Blog
Microsoft Security Blog
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
Martin Fowler
Martin Fowler
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
Last Week in AI
Last Week in AI
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
V
V2EX
G
Google Developers Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How I Built a Production-Ready Multi-Tenant SaaS Boilerpl...
Nur Nahar · 2026-06-03 · via DEV Community

I got tired of starting from zero every time.

Every project I worked on needed the same things — authentication, organizations, billing, admin panel. And every time I had to build them again from scratch. Copy code from old projects, fix bugs that come from copying, spend the first two weeks just getting the foundation ready before touching the actual product.

So I decided to build it once, properly, and never do it again.


What I built

A full MERN stack boilerplate that includes everything a SaaS product needs to launch:

  • JWT authentication with refresh token rotation
  • Multi-tenancy — users can create and switch between organizations
  • Role-based access control with three roles: owner, admin, member
  • Stripe subscriptions with checkout, billing portal, and webhook handling
  • Super admin dashboard with platform stats, user management, and plan overrides
  • 52 integration tests covering every feature

The whole thing is deployed — frontend on Netlify, backend on Railway, MongoDB Atlas, Upstash Redis.


The hard parts nobody talks about

Cross-domain cookies
This one took me longer than I want to admit.

When your frontend is on netlify.app and your backend is on railway.app, cookies don't just work. Browsers block cross-domain cookies by default for security reasons.

The fix is setting sameSite: 'none' and secure: true on your cookies. But here's the thing — most tutorials show sameSite: 'strict' which works perfectly on localhost and then completely breaks in production. I spent a few hours debugging this before finding the issue.

For local development I store refresh tokens in HTTP-only cookies with sameSite: 'strict'. For production it switches to sameSite: 'none' with secure: true. Never localStorage — that's asking for XSS trouble.

Stripe webhook verification
Stripe sends events to your server after a payment. Simple enough in theory. In practice, it only works if you set up the raw body parser before express.json() in your middleware stack.

I had express.json() at the top and kept getting signature verification errors. Spent way too long on this. The fix is mounting your webhook route with express.raw() before the JSON parser middleware. Order matters.

Also your local webhook secret (from stripe listen) is completely different from your production webhook secret (from the Stripe dashboard). They're not the same. Don't mix them up.

Tenant data isolation
This sounds complicated but the concept is simple — every piece of data in the database has an orgId field, and every query filters by it.

The tricky part is making sure you never forget to add it. I solved this with a requireOrg middleware that runs before any org-scoped route. It reads the activeOrgId from the user's JWT, fetches the org from MongoDB, and attaches it to req.org. Every route handler then uses req.org._id for its queries automatically.

The harder problem is token rotation. When a user switches organizations, you need to issue a new access token with the updated activeOrgId. Otherwise the user switches org in the UI but the token still carries the old org and queries return wrong data.

Tests polluting the real database
This was an embarrassing one. My Jest tests were writing to the actual MongoDB database instead of an isolated test environment. After running the test suite I had dozens of fake "Test Org" records in my real database.

The fix is mongodb-memory-server — it spins up a real MongoDB instance in memory for each test suite and tears it down after. Your real database never gets touched. Every project should have this set up from day one.


What I learned

Read the docs properly. Most of my debugging time was spent on things that are clearly documented — I just skimmed instead of reading carefully. The Stripe webhook documentation explicitly mentions the raw body parser requirement. I just didn't read that far.

Test in production early. I tested everything on localhost and it all worked perfectly. Then I deployed and cross-domain cookies broke, environment variables weren't loading, the webhook URL was wrong. Deploy early and test the real thing, not just localhost.

Git commit before every major change. I started doing git commit before every Claude Code session as a habit. Saved me multiple times when the AI made changes I didn't expect and I needed to roll back cleanly.

Environment variables are not magic. They only work if you configure them in the right place. Local .env and Railway environment variables are completely separate. Changing one does nothing to the other. Sounds obvious but it's easy to forget when you're deep in debugging.


The stack

  • Frontend: React 18, Vite, TypeScript
  • Backend: Node.js, Express, TypeScript
  • Database: MongoDB with Mongoose
  • Cache: Redis with ioredis
  • Auth: JWT, bcrypt, HTTP-only cookies
  • Payments: Stripe
  • Testing: Jest, Supertest, mongodb-memory-server
  • Infrastructure: Docker, Docker Compose, pnpm workspaces
  • Deployed on: Netlify, Railway, MongoDB Atlas, Upstash Redis

Try it

Live demo: https://multi-tenant-saas-boilerplate.netlify.app

You can register, create an organization, invite members, and go through the Stripe checkout flow with test cards. Everything works end to end.

If you want the full source code with all 52 tests, the deployment guide, and the scripts, I'm selling it on Gumroad:
https://momotaz.gumroad.com/l/qyhlh

If you've built something similar or ran into the same issues, I'd love to hear how you solved them. Drop a comment below.