Skip to content

About

REST API for a course marketplace: JWT auth, role-based access, Zod validation, rate limiting, PostgreSQL via Prisma (37 models). Node.js, Express, TypeScript.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Ed-Tech Platform — Backend

REST API for the Ed-Tech Platform. Handles authentication, course/section/lesson management, enrollment, and per-lesson progress tracking.

Pairs with the Ed-Tech Platform frontend (React + Vite).

Live API: https://ed-tech-platform-backend-ten.vercel.app (health check at /api/health), used by the live frontend.

Deployment

Runs on Vercel as a serverless Express function, with PostgreSQL on Neon. Each production deploy runs vercel-build:

  1. prisma migrate deploy applies pending migrations over the direct (unpooled) connection.
  2. prisma db seed (prisma/seed.ts) upserts the demo student and instructor and rebuilds the three demo courses. On Vercel this only happens when DEMO_MODE=true. Without it the step is skipped, because the seed deletes all enrollments and progress on the demo courses. Set DEMO_MODE=true only on the public demo project, never on a database with real users.
  3. tsc builds the app.

Production environment variables: DATABASE_URL and DATABASE_URL_UNPOOLED (from the Neon integration), JWT_SECRET, and CLIENT_URL (comma-separated allowed origins), plus DEMO_MODE=true on the demo deployment only.

Tech stack

  • Node.js + Express + TypeScript
  • PostgreSQL via Prisma ORM (prisma/schema.prisma)
  • Zod for request validation
  • Cookie sessions: httpOnly access/refresh cookies, server-side Session table with refresh rotation and reuse detection; bcrypt (cost 12) password hashing
  • Postgres-backed rate limits on auth endpoints; password reset and email verification via a pluggable mailer (Resend)
  • Helmet, CORS, and express-rate-limit for hardening

Project layout

src/
├── controllers/   # business logic, one file per resource
├── routes/        # Express routers, one file per resource
├── middlewares/   # authenticate, requireRole, error + 404 handlers
├── config/        # singleton Prisma client
├── utils/         # CustomError
└── index.ts       # app bootstrap + route wiring
prisma/
├── schema.prisma  # data model (PostgreSQL)
└── migrations/    # migration history

API surface (v1)

  • POST /api/auth/signup, POST /api/auth/login
  • GET /api/courses (filter/search/paginate), GET /api/courses/:id, GET /api/courses/mine, POST /api/courses, PUT /api/courses/:id, PUT /api/courses/:id/publish
  • POST /api/courses/:courseId/sections, PUT /api/sections/:id, DELETE /api/sections/:id
  • POST /api/sections/:sectionId/subsections, PUT /api/subsections/:id, DELETE /api/subsections/:id
  • POST /api/courses/:courseId/enroll, GET /api/courses/:courseId/enrollment, GET /api/enrollments/me
  • GET /api/progress/:courseId, POST /api/progress/:courseId/subsections/:subSectionId

Full request/response details are in docs/API.md.

All responses follow { success: true, data } on success and { hasError: true, message, errors } on failure.

Getting started

Prerequisites

  • Node.js 18+
  • PostgreSQL 14+

Setup

npm install
cp .env.example .env        # then edit values
npx prisma migrate dev      # create + apply schema
npm run dev                 # ts-node dev server at http://localhost:3000

Required environment variables (the server exits on startup if DATABASE_URL or JWT_SECRET is missing):

DATABASE_URL="postgresql://user:password@localhost:5432/edtech_dev?schema=public"
JWT_SECRET="change-me-to-a-long-random-secret-min-32-chars"
CLIENT_URL="http://localhost:5173"   # optional, CORS origin
PORT=3000                            # optional
NODE_ENV="development"               # optional

Scripts

npm run dev      # ts-node dev server
npm run build    # tsc compile to dist/
npm start        # run compiled dist/index.js
npm run admin:grant -- [email protected]   # make an existing account ADMIN (admins can't sign up)
npm run report:unsafe-media                  # read-only: list stored non-https media URLs

In development, emails (verification, password reset) are printed to the server console.

Useful Prisma commands:

npx prisma studio                     # browse the database
npx prisma migrate dev --name <name>  # create + apply a migration
npx prisma generate                   # regenerate the client after schema edits

Testing

CI

Integration tests (Vitest + Supertest) call the real Express app against a real PostgreSQL database. Nothing is mocked. They cover:

  • Auth: signup and login, admin self-signup blocked, field-level validation errors, the same 401 for a wrong password and an unknown email, missing and forged tokens
  • Access control: students can't create courses, and instructors can't edit other instructors' courses
  • Visibility: drafts are hidden from the public catalog and from everyone except their instructor
  • Enrollment: free courses only, exactly once, no drafts
  • Progress: percentage tracking, idempotent completion, lessons from other courses rejected
  • Security: https-only media URLs (no javascript:/data:), lesson content withheld from users who aren't entitled, banned and deactivated accounts blocked at login and on every request
  • Validation: bad ids and catalog filters return 400 (not 500), page size capped at 50, malformed JSON is 400 and oversized bodies 413, concurrent enrollment is 409
  • Updates: partial PUTs leave unsent fields unchanged
  • Ordering: sections and lessons come back in curriculum order
  • Sessions: cookie attributes, refresh rotation and replay detection, logout / logout-all, legacy Bearer flag, CSRF Origin check, algorithm pinning, minimum secret length
  • Rate limits: per-account and per-IP login throttling, signup and refresh limits, shared Postgres counters, failed-login audit trail
  • Account lifecycle: password policy and breach check, cost upgrade, forgot/reset, change password, email verification
  • Instructor approval: signup never grants instructor, application and admin review (including concurrent decisions), admin-only featuring, admin:grant
createdb edtech_test
DATABASE_URL="postgresql://localhost:5432/edtech_test" npm test

Demo coaching centre for pitches and the walkthrough video:

DEMO_CENTRE_PASSWORD='choose-a-password' APP_URL=https://your-frontend.vercel.app npm run demo:centre

It creates "Sharma Classes": an owner, 2 teachers, 12 students, 2 batch courses and varied progress. It only runs when you run it, never on deploy, and refuses if the centre already exists. All accounts use example.com emails. They share the password you set in DEMO_CENTRE_PASSWORD, which is required and never printed.

CI runs the suite on every pull request and on main against a Postgres 16 service container. It also runs the frontend's Playwright end-to-end tests (from the frontend's main) against this backend, so an API change that breaks the UI fails before it merges. CodeQL scans both repositories, and Dependabot proposes dependency updates weekly. To report a vulnerability, see SECURITY.md.

Notes on scope

The Prisma schema models many future features (quizzes, assignments, certificates, discussions, notifications, analytics, taxonomy, etc.). Only the core learning-loop models are wired to routes in v1: User, Course, Section, SubSection, Enrollment, CourseProgress (+ SubSectionProgress for per-lesson completion), and LoginHistory.

About

REST API for a course marketplace: JWT auth, role-based access, Zod validation, rate limiting, PostgreSQL via Prisma (37 models). Node.js, Express, TypeScript.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages