High-performance, role-guarded backend engine powering the StartupForge talent & co-founder ecosystem.
Built on Express 5 and the native MongoDB 7 Driver (no ORM overhead). Delivers token-verified authentication, multi-tier RBAC authorization, complex aggregation pipelines, Stripe webhook subscription ingestion, and automated bidirectional notification dispatching.
Quick Start β’ Engineering Pillars β’ Architecture β’ API Reference β’ Security & RBAC β’ Database β’ Configuration β’ Deployment
- Executive Overview
- Core Engineering Pillars
- System Architecture
- Complete API Reference
- Security & Authentication Architecture
- Database Collections & Aggregations
- Environment Variables
- Quick Start & Local Setup
- Deployment Architecture
- Author & License
The StartupForge Server is the mission-critical backend engine supporting the StartupForge platform. It manages all persistent business logic, role-aware entity relationships, and transactional workflows between:
- Founders: Creating venture profiles, post-quota gated opportunities, and adjudicating candidate applications.
- Collaborators: Discovering verified startups, optimistically bookmarking listings, and submitting vetted applications.
- Administrators: Moderating startup submissions, auditing Stripe payment transactions, and enforcing platform moderation policies.
The server operates synchronously with the companion Next.js client: while the client handles authentication session creation via better-auth, this Express engine acts as the authoritative gatekeeper by validating bearer session tokens directly against MongoDB Atlas on every protected request.
| Pillar | Engineering Detail | System Advantage |
|---|---|---|
| π Native MongoDB Driver | Uses mongodb@^7.5.0 without Mongoose ODM abstractions; Stable API v1 (strict: true). |
Transparent aggregation pipelines ($lookup, $match, $facet), lower memory overhead, and lightning-fast execution. |
| π‘οΈ Token-Verified RBAC | Custom verifyToken middleware resolves active bearer tokens against MongoDB session records. |
Immediate token revocation detection with zero stale JWT session vulnerabilities. |
| π Strict Anti-IDOR Enforcement | Every mutation checks ownership against req.user.id or req.user.email directly in the route handler. |
Eliminates Insecure Direct Object References; users can never inspect or mutate foreign records. |
| β‘ Smart Denormalization | Founder credentials (name, email, image, bio) are stamped on startup & opportunity documents and re-synced in batch. |
Eliminates N+1 database queries on public directory listings while preserving data privacy. |
| π Event-Driven Notifications | Automatic dispatching of targeted in-app alerts on status changes (Application Accepted/Rejected, Startup Vetting, Plan Upgrades). | Real-time member awareness without requiring third-party webhook dependencies. |
| π Resilient Cloud Networking | Hardcoded custom DNS lookup resolvers (1.1.1.1 & 1.0.0.1) initialized before database pooling. |
Prevents transient DNS resolution failures when connecting to MongoDB Atlas within serverless environments. |
π View Raw Mermaid Architecture Source
flowchart TB
subgraph ClientLayer["π₯οΈ Frontend Consumer (Next.js 16 App Router)"]
ClientReq["Client / Server Action Request"]
BearerToken["Authorization: Bearer <session_token>"]
end
subgraph MiddlewareStack["π‘οΈ Express Middleware & Security Layer"]
DNS["Custom DNS Resolver (1.1.1.1 / 1.0.0.1)"]
CORS["CORS (Strict CLIENT_URL Allowlist)"]
Parser["express.json Body Parser"]
TokenVerifier["verifyToken (Validates Session Collection)"]
RoleGuard["requireAnyRole (Founder / Collaborator / Admin)"]
IDORCheck["Handler-Level Ownership & Tenant Assertion"]
end
subgraph ServiceModules["βοΈ Core Route Modules (index.js)"]
SubModule["Subscriptions & Stripe Receipts"]
StartupModule["Startups & Approval Engine"]
OppModule["Opportunities & Quotas"]
AppModule["Applications Pipeline"]
BookmarkModule["Bookmarks & Favorites"]
UserModule["User Profiles & Governance"]
NotifyModule["Notification Dispatcher"]
end
subgraph StorageLayer["ποΈ MongoDB Atlas Persistence (Native Driver v7)"]
DBSessions[("session")]
DBUsers[("user")]
DBStartups[("startups")]
DBOpportunities[("opportunities")]
DBApplications[("applications")]
DBBookmarks[("bookmarks")]
DBSubscriptions[("subscriptions")]
DBPlans[("plans")]
DBNotifications[("notifications")]
end
ClientReq --> DNS
DNS --> CORS
CORS --> Parser
Parser --> TokenVerifier
BearerToken -.-> TokenVerifier
TokenVerifier -->|Fetch Session Record| DBSessions
DBSessions -->|Hydrate User Profile| DBUsers
TokenVerifier --> RoleGuard
RoleGuard --> IDORCheck
IDORCheck --> ServiceModules
SubModule --> DBSubscriptions
SubModule --> DBUsers
StartupModule --> DBStartups
OppModule --> DBOpportunities
AppModule --> DBApplications
BookmarkModule --> DBBookmarks
UserModule --> DBUsers
NotifyModule --> DBNotifications
| Badge | Meaning |
|---|---|
π Public |
No authorization token required |
πͺͺ Token |
Requires valid session token (Authorization: Bearer <token>) |
π’ Founder |
Authenticated account with founder or admin role |
π€ Collaborator |
Authenticated account with collaborator or admin role |
π Admin |
Administrator access only (bypasses ownership checks) |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
GET |
/ |
API health check and server connectivity status probe. | π Public |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/subscriptions |
Ingests Stripe payment session, idempotently records receipt, updates user plan, and dispatches admin notifications. |
πͺͺ Token |
GET |
/api/subscriptions |
Returns all recorded subscription payment transactions sorted newest first (Admin ledger). | π Admin |
GET |
/api/plans |
Retrieves platform plan definitions, quotas, and feature entitlements (?plan_id= filter supported). |
πͺͺ Token |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/startup |
Registers a new startup profile. Founder credentials stamped server-side; triggers admin review alerts. | π’ Founder |
PATCH |
/api/startup/:id |
Modifies or resubmits a startup profile (owner), or transitions status to Approved / Rejected (admin). Cascades status to opportunities. |
πͺͺ Owner / π Admin |
DELETE |
/api/startup/:id |
Permanently deletes a startup profile and verifies ownership. | πͺͺ Owner / π Admin |
GET |
/api/my/startup |
Retrieves startups owned by the authenticated founder (?startupId= optional filter). |
π’ Founder |
GET |
/api/startups |
Searchable startup catalog with faceted filters: ?search=, ?industry=, ?funding_stage=, and ?page=&limit=. |
π Public |
GET |
/api/featured/startups |
Returns the 5 most recently created and verified startups for homepage strips. | π Public |
GET |
/api/startup/:id |
Returns complete details for a single startup by ObjectId. |
π Public |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/opportunity |
Publishes a new open role for a verified startup. Enforces server-side founder identity stamping. | π’ Founder |
PATCH |
/api/opportunity/:id |
Edits an existing opportunity. Automatically syncs founder profile attributes upon update. | πͺͺ Owner / π Admin |
DELETE |
/api/opportunity/:id |
Removes an opportunity listing after verifying ownership. | πͺͺ Owner / π Admin |
GET |
/api/my/opportunities |
Returns all opportunities posted by the authenticated founder (?startupId= optional filter). |
π’ Founder |
GET |
/api/opportunities |
Paginated opportunity directory with full-text regex search (?search=), ?workType=, ?industry=, and ?page=&limit=. |
π Public |
GET |
/api/featured/opportunities |
Fetches the 5 most recently posted active opportunities. | π Public |
GET |
/api/opportunity/:id |
Detailed view of a single opportunity record. | π Public |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/application |
Submits candidate application to an opportunity. Stamps applicant credentials and dispatches alert to founder. | π€ Collaborator |
PATCH |
/api/application/:id |
Founders make Accepted or Rejected decisions. Automatically notifies candidate of status outcome. |
π’ Founder / π Admin |
GET |
/api/founder/applications |
Returns all candidate applications submitted to the authenticated founder's startups. | π’ Founder |
GET |
/api/my/applications |
Returns the authenticated collaborator's applications enriched with opportunity details via $lookup. Blocks cross-user snooping. |
π€ Collaborator |
DELETE |
/api/application/:id |
Withdraws or cancels an application (caller must be applicant, receiving founder, or admin). | πͺͺ Owner / π’ Founder |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/bookmark |
Saves an opportunity to personal bookmarks. Idempotently returns existing bookmark if duplicate. | πͺͺ Token |
DELETE |
/api/bookmark/:id |
Removes a saved bookmark record. Scoped strictly to the caller's userId. |
πͺͺ Owner / π Admin |
GET |
/api/my/bookmarks |
Returns all saved bookmarks for the authenticated collaborator. Prevents IDOR data leaks. | π€ Collaborator |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
GET |
/api/user/profile/:id |
Retrieves sanitized member profile. Permitted only for self or platform admins. | πͺͺ Self / π Admin |
PATCH |
/api/user/profile/:id |
Updates user profile fields (name, image, skills, bio) through a strict allowlist. |
πͺͺ Self / π Admin |
PATCH |
/api/user/:id |
Moderates user account status (e.g. active / banned). |
π Admin |
GET |
/api/users |
Returns list of platform users with sanitized sensitive credentials for administration console. | π Admin |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
GET |
/api/notifications |
Returns the 30 most recent user notifications and aggregate unreadCount. Admins also receive broadcast alerts. |
πͺͺ Token |
PATCH |
/api/notifications/mark-all-read |
Marks all unread notifications as read for the authenticated caller. | πͺͺ Token |
PATCH |
/api/notifications/:id/read |
Marks a single notification record as read after asserting caller ownership. | πͺͺ Token |
The server adopts a Zero-Trust Security Model tailored for distributed SaaS platforms:
Instead of issuing stateless JWTs that cannot be revoked immediately, the API verifies bearer tokens against the session collection created by better-auth:
// Verification extracts Bearer token, checks expiration, and hydrates user:
const sessionRecord = await sessionCollection.findOne({
token: tokenString,
expiresAt: { $gt: new Date() },
});
if (!sessionRecord) return res.status(401).json({ message: "Invalid or expired session" });The requireAnyRole middleware accepts multiple allowable roles and prevents bypass exploits:
const requireAnyRole = (...roles) => (req, res, next) => {
const currentRole = String(req.user.role || req.user.accountType || "").toLowerCase();
if (!roles.map(r => r.toLowerCase()).includes(currentRole)) {
return res.status(403).json({ message: "Forbidden: insufficient permissions" });
}
next();
};Clients are never trusted to provide their own author, founder, or applicant ID in request payloads:
startupId,founderId,collaboratorId, andapplicantEmailare populated strictly fromreq.user.- Even if a malicious user alters their client payload to target another account, the server overwrites the fields with verified session data.
All user documents returned by the API pass through a strict sanitization filter:
const SENSITIVE_FIELDS = ["password", "passwordHash", "hashedPassword", "token", "sessionToken"];Operating on MongoDB Atlas using the native Node.js driver:
| Collection | Schema Focus | Critical Index & Query Pattern |
|---|---|---|
user |
Account credentials, persona (founder / collaborator / admin), plan, status. |
Indexed on email, role, accountType. |
session |
Active better-auth tokens, user references, and expiresAt timestamps. |
TTL index on expiresAt for automatic cleanup. |
startups |
Company profiles, funding stage, industry, website, logo URL, approval status. | Compound text index on name, industry, description. |
opportunities |
Open positions, title, requirements, salary/equity, work type, deadline, quotas. | Indexed on startupId, workType, deadline. |
applications |
Candidate resumes, pitch messages, current evaluation status (Pending / Accepted / Rejected). |
Composite $lookup joining opportunities collection. |
bookmarks |
Saved positions keyed by opportunityId and userId. |
Unique compound index on { opportunityId: 1, userId: 1 }. |
subscriptions |
Stripe payment sessions, amount in cents, plan tier, currency, timestamps. | Unique index on session_id (idempotency barrier). |
plans |
Quota tiers definitions (e.g. Free Starter, Pro, Enterprise). | Keyed by plan_id. |
notifications |
In-app alerts, target recipientId, event type, message, read flags. |
Indexed on { recipientId: 1, isRead: 1, createdAt: -1 }. |
Create a .env file in the root of startup-forge-server/:
# -----------------------------------------------------------------------------
# HTTP RUNTIME CONFIGURATION
# -----------------------------------------------------------------------------
PORT=5000
# -----------------------------------------------------------------------------
# CORS SECURITY
# Pinned to client domain (No wildcards)
# -----------------------------------------------------------------------------
CLIENT_URL="http://localhost:3000"
# -----------------------------------------------------------------------------
# MONGODB ATLAS CONNECTION (Native Driver)
# -----------------------------------------------------------------------------
MONGODB_URI="mongodb+srv://<username>:<password>@cluster0.mongodb.net/?appName=Cluster0"
DB_NAME="StartupForge"- Node.js:
v18.17.0or newer - npm or pnpm
- MongoDB: Local database or free MongoDB Atlas Cluster
git clone https://github.com/takebul/startup-forge-server.git
cd startup-forge-servernpm installCreate a .env file matching the specifications above.
npm startOpen your terminal or browser:
curl http://localhost:5000/
# Output: "StartupForge server is running fine!"The server is configured for automated continuous deployment on Vercel via serverless lambdas:
- Live URL: https://startup-forge-server-nine.vercel.app/
- Serverless Adapter:
vercel.jsonbundlesindex.jsusing@vercel/nodeand forwards all HTTP methods through a wildcard route:
{
"version": 2,
"builds": [
{ "src": "index.js", "use": "@vercel/node" }
],
"routes": [
{ "src": "/(.*)", "dest": "index.js", "methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] }
]
}- Cloudflare DNS Resolver: High-performance explicit DNS resolution (
1.1.1.1and1.0.0.1) is configured at boot time to prevent cold-start latency when resolving MongoDB Atlas connection endpoints in serverless microVMs.
Takebul Islam
Full-Stack Engineer building robust, scalable APIs and modern web applications.
Distributed under the ISC License β see package.json for full terms.