mdSHash/NueralPath

AI Engineer Mastery Terminal — RAG, embeddings, LLMs, agents, production AI. Next.js 15 + TypeScript + Prisma + Gemini 3.1 Pro Preview.

0

stars

0

commits

TypeScript

primary language

Jun 2, 2026

updated

nueral-path.vercel.app

README

NeuralPath

NeuralPath

An engineering-terminal learning platform for senior AI engineers. Six modules · forty-eight lessons · interview simulator · AI-graded code labs.

▸ Live demo — nueral-path.vercel.app

Next.js TypeScript Tailwind Prisma Gemini Deployed on Vercel

Live demo · Features · Architecture · Quick start · API surface · Security


Why this exists

Most AI-engineering content stops at "what is RAG". NeuralPath goes the other way: production-grade trade-offs first, code labs that ask you to implement, an interview simulator that scores you on correctness, depth, and clarity, and an in-browser Python runtime so you actually run the code you write.

Built as a personal mastery tool for top-tier AI engineer interviews while working on production AI systems at IBM. Single-user, local-first, deployable to a free Vercel + Neon stack in under three minutes.

The aesthetic is intentional — deep charcoal, electric cyan, terminal-grid backgrounds. Bloomberg meets sci-fi mission control, not another purple-gradient AI dashboard.


Features

48 lessons across 6 modulesRAG (naïve → CRAG → eval), embeddings (with tokenization + transformer forward-pass internals), LLM models (transformer architecture + inference internals), agents, production AI (with HNSW internals), enterprise patterns. Each lesson: theory body, animated diagram, decision card, interview gotchas, scored quiz.
Three-mode hands-on labsWalkthrough reveals code section by section with key-points and "what to notice" callouts. Practice gives you starter-code stubs and AI-graded verification. Experiment is a free Monaco editor with a Gemini code-explainer. Optional Pyodide Web Worker actually runs your Python in the browser.
Interview simulatorConceptual / system-design / coding / behavioral modes × three difficulties × three company types. Each answer scored on correctness, depth, and clarity, with a written critique and ideal answer. Sessions persist; history feeds the readiness score.
AI tutor chatStreaming responses, lesson-aware context, persistent history.
Animated SVG diagramsRAG pipeline, embedding space, chunking comparison, model decision tree, agent loop, LangGraph state machine, hybrid-search RRF, RAGAS eval radar.
Concept glossary~130 terms with high/medium/low frequency badges, lesson cross-links, and on-demand Gemini "Simplify" explanations.
Progress telemetryRecharts module-mastery bar chart, score-trajectory line chart with 5-session moving average, quiz-score scatter, recent-sessions log.

Tech stack

LayerChoiceWhy
FrameworkNext.js 15 App RouterRSC + streaming for the tutor; Node runtime for API routes; built-in middleware for CSRF + rate limit
LanguageTypeScript strict modeType safety from prompt schemas to UI
StylingTailwind CSS 3.4Custom dark engineering-terminal tokens
MotionFramer Motion 11Page transitions, diagram animations, panel reveals
EditorMonaco (@monaco-editor/react)Same editor as VS Code; lazy-loaded
Python runtimePyodide 0.26Real CPython + NumPy in a Web Worker
ChartsRechartsDark-themed analytics
ORM / DBPrisma 5 + Postgres (Neon)Single schema swaps to SQLite for local dev
LLM@google/generative-ai · gemini-3.1-pro-previewServer-side only — key never reaches the browser
ValidationZodPer-route request schemas + env validation
Markdownreact-markdown + remark-gfmNo dangerouslySetInnerHTML anywhere

Architecture

┌────────────────────────────────────────────────────────────────┐
│  Browser                                                       │
│  • App Router pages (RSC) — dashboard, lessons, glossary,      │
│    progress, interview, tutor, playground                      │
│  • Client islands — Monaco, Recharts, Framer Motion, streaming │
│    chat, Pyodide Web Worker                                    │
└──────────────────────────┬─────────────────────────────────────┘
                           │  fetch (same-origin, rate-limited)
┌──────────────────────────▼─────────────────────────────────────┐
│  middleware.ts                                                 │
│  • per-IP token-bucket rate limit (120 req/min)                │
│  • same-origin enforcement on POST/PUT/PATCH/DELETE            │
└──────────────────────────┬─────────────────────────────────────┘
                           │
┌──────────────────────────▼─────────────────────────────────────┐
│  Next.js 15 — Node runtime API routes                          │
│                                                                │
│  /api/health              env + db probe                       │
│  /api/chat                streaming Gemini tutor               │
│  /api/interview/*         session, generate, evaluate, log     │
│  /api/explain             code walkthrough on demand           │
│  /api/walkthrough         lab walkthrough generation           │
│  /api/verify              AI-graded lab task verification      │
│  /api/simplify            ELI-junior helper                    │
│  /api/harder              escalate interview question          │
│  /api/progress            lesson progress + readiness          │
│  /api/note                per-lesson notes                     │
│                                                                │
│  Each route:                                                   │
│    • validates input via Zod (lib/validation.ts)               │
│    • wraps Gemini calls in retry-with-backoff (lib/retry.ts)   │
│    • emits structured JSON logs (lib/logger.ts)                │
└──────────┬─────────────────────────────────────────┬───────────┘
           │                                         │
   ┌───────▼─────────┐                       ┌───────▼─────────┐
   │  Prisma · Neon  │                       │  Gemini API     │
   │  Postgres       │                       │  3.1 Pro        │
   │                 │                       │  preview        │
   │  Users          │                       │                 │
   │  LessonProgress │                       │  Server-side    │
   │  InterviewSession                       │  only — key     │
   │  InterviewQuestion                      │  never reaches  │
   │  CodeSubmission │                       │  the browser    │
   │  Note · Badge   │                       └─────────────────┘
   │  ChatMessage    │
   └─────────────────┘

Quick start

git clone git@github.com:mdSHash/NueralPath.git
cd NueralPath

# 1. install
npm install --legacy-peer-deps

# 2. configure
cp .env.example .env
# then edit .env and set GEMINI_API_KEY + DATABASE_URL

# 3. database
npm run db:push     # creates the schema in your Postgres
npm run db:seed     # creates the default user

# 4. dev server
npm run dev

Open http://localhost:3000.

For local development without Postgres, flip provider = "sqlite" in prisma/schema.prisma and use DATABASE_URL=file:./dev.db.


Deploy your own

Cloning to a fresh stack takes about three minutes:

Deploy with Vercel

  1. Click the button above (or import mdSHash/NueralPath in the Vercel dashboard).
  2. Provision a free Postgres at neon.tech and copy the pooled connection string.
  3. Set Vercel env vars:
    • GEMINI_API_KEY — from Google AI Studio
    • DATABASE_URL — your Neon pooled URL
  4. Deploy. Vercel runs npm run vercel-build, which regenerates the Prisma client, pushes the schema, and builds Next.js — the database is initialised automatically.
  5. Hit <your-url>/api/health to verify.

Curriculum

#ModuleFocusLessons
1RAGNaive → Advanced → Modular → Agentic → GraphRAG → Multimodal → CRAG → Eval10
2EmbeddingsModels, chunking, vector DBs, hybrid search, multilingual, tokenization, encoder forward pass9
3LLM ModelsSelection, OS vs proprietary, watsonx, routing, transformer architecture, inference internals10
4Agents & OrchestrationReAct, LangGraph, multi-agent, tool design, memory, eval6
5Production AIObservability, evals, guardrails, latency, cost, CI/CD, HNSW internals8
6Enterprise / IBMMulti-tenant RAG, MQ integration, Azure OpenAI, responsible AI, ROI5

Each lesson includes: theory body (Markdown) · animated SVG diagram (where applicable) · key takeaways · decision card (when-to-use / not / trade-offs) · interview gotchas · scored quiz · optional code lab.


Project layout

app/
  page.tsx                     dashboard
  learn/                       curriculum index + lesson viewer
  playground/                  standalone Monaco labs
  interview/                   interview simulator
  chat/                        AI tutor
  glossary/                    searchable term dictionary
  progress/                    charts + recent sessions
  api/                         12 endpoints — Gemini + persistence + health
components/
  ui/                          design-system primitives
  layout/                      sidebar, topbar shell
  dashboard/                   hero, learning map, readiness, next lesson
  lesson/
    LessonClient.tsx           viewer shell
    KeyTakeaways · DecisionCard · Gotchas · Quiz · DiagramSlot
    lab/
      LabTabs.tsx              walkthrough / practice / experiment switch
      WalkthroughLab.tsx       sections with reveal pacing
      PracticeLab.tsx          editor + verify + reference solution
      ExperimentLab.tsx        free editor + AI explainer
      PyodideRunner.tsx        Web-Worker Python runtime panel
  interview/                   setup, runner, summary
  diagrams/                    eight animated SVG concept diagrams
hooks/
  usePyodide.ts                worker lifecycle + run helper
lib/
  curriculum/                  six module files + glossary + interview seed
  gemini.ts                    server-only SDK wrapper with retries
  env.ts                       Zod-validated process.env
  validation.ts                per-route + lab request schemas
  logger.ts                    structured JSON logger
  retry.ts                     exponential-backoff helper
  db.ts                        Prisma client singleton
public/
  pyodide-worker.js            Web Worker that hosts Pyodide
prisma/
  schema.prisma                Postgres schema
  seed.ts                      default user + starter progress
middleware.ts                  rate limit + same-origin enforcement
next.config.ts                 security headers + CSP

API surface

All routes live at /api/*, run on the Node runtime, validate request bodies with Zod, and emit structured logs on failure.

Method · RouteBody / paramsReturns
GET /api/health{ status, model, db, time }
POST /api/chat{ message, moduleId?, lessonId?, history? }streamed text/plain (Gemini tokens)
GET /api/chat{ messages[] } recent tutor history
POST /api/interview/session{ mode, companyType, role, difficulty, module? }{ sessionId }
GET /api/interview/session{ sessions[] }
POST /api/interview/generate{ mode, companyType, role, difficulty, module?, count? }{ questions[], source }
POST /api/interview/evaluate{ question, userAnswer, role, difficulty, mode }{ scoreCorrectness, scoreDepth, scoreClarity, feedback, idealAnswer, missingConcepts[] }
POST /api/interview/questionfull per-question record{ id }
POST /api/explain{ code, language? }{ explanation }
POST /api/walkthrough{ labTitle, language, starterCode, expectedConcepts? }{ sections[] }
POST /api/verify{ taskPrompt, taskDescription, language, userCode, referenceSolution? }{ passed, score, feedback, hints[] }
POST /api/simplify{ concept }{ explanation }
POST /api/harder{ question, mode? }{ question }
GET /api/progressaggregate readiness telemetry
POST /api/progress{ moduleId, lessonId, status?, quizScore?, addTime? }updated LessonProgress row
GET /api/note?moduleId&lessonId{ notes[] }
POST /api/note{ moduleId, lessonId, body }{ note }
DELETE /api/note{ id }{ ok }

Mutating routes require Origin === Host. Cross-origin → 403. Rate-limited at 120 req/min per IP.


Environment variables

NameRequiredDefaultPurpose
GEMINI_API_KEYyesServer-side Google Generative AI key. Never sent to the browser.
GEMINI_MODELnogemini-3.1-pro-previewOverride the model name.
DATABASE_URLyesPrisma datasource. Postgres connection string (Neon, Supabase, Vercel Postgres). For SQLite dev, set provider = "sqlite" in prisma/schema.prisma and use file:./dev.db.
NODE_ENVnodevelopmentproduction enables HSTS.

.env is gitignored. Use .env.example as the template and never commit a real key.


Security

The app ships the controls a public-facing Next.js app should have, even though it's designed for single-user use.

LayerControl
NetworkTLS-only via Vercel; HSTS in production builds (Strict-Transport-Security: max-age=63072000; includeSubDomains; preload)
BrowserStrict CSP (default-src 'self'; Gemini connect-src restricted), frame-ancestors 'none', X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Resource-Policy: same-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), X-Powered-By removed
Edgemiddleware.ts enforces same-origin on every mutating /api/* request and applies a per-IP token bucket (120 req/min)
AppZod request-body validation on every API route; Zod-validated process.env at startup; exponential-backoff retry around every Gemini call; structured JSON logging
DataPrisma parameterised queries throughout; no raw SQL; react-markdown + remark-gfm everywhere — no dangerouslySetInnerHTML
SecretsGemini SDK imported only inside app/api/** and lib/gemini.ts; no NEXT_PUBLIC_* keys; .env gitignored
Runtime isolationPyodide runs inside a Web Worker, sandboxed away from the main thread

npm audit is clean against direct dependencies. Next.js is pinned to 15.5.19+ which patches the critical RCE in the React Flight protocol (GHSA-9qr9-h5gf-34mp) and the middleware authorization-bypass (GHSA-f82v-jwr5-mffw) that affected earlier 15.x.

Out of scope

  • Authentication. Single-user app; default user user_default is auto-created. To go multi-tenant: add NextAuth, key Prisma queries on session.user.id, tighten the CSRF check.
  • Distributed rate limiting. Token bucket lives in process memory. For multi-instance deploys swap to Upstash Ratelimit; the middleware shape stays the same.

Scripts

ScriptWhat it does
npm run devNext.js dev server on :3000
npm run buildProduction build (no DB migration — for local builds)
npm run vercel-buildWhat Vercel runs: prisma generate && prisma db push --accept-data-loss && next build
npm run startStart the production build
npm run lintESLint via next lint
npm run db:pushPush the Prisma schema to your DB
npm run db:generateRegenerate the Prisma client
npm run db:seedSeed the default user + starter progress

Troubleshooting

Could not resolve dependency on npm install. Some peers want React 19. Rerun with npm install --legacy-peer-deps.

/api/health returns db: "fail". Prisma can't reach your DB. Check DATABASE_URL. For Neon, use the pooled connection string (the URL with -pooler in the host).

Chat / interview / explain returns 502. Either GEMINI_API_KEY is missing or the model returned an error. Check the dev-server console — lib/logger.ts emits a structured line with the failing route.

Monaco fails to load. Loaded via next/dynamic with ssr: false. Ensure JavaScript is enabled and the CSP shipped here isn't being overridden by your platform.

Pyodide takes 10–20 s to start. Expected on first use — it downloads ~10 MB from cdn.jsdelivr.net and initialises a Web Worker. Subsequent runs are instant.

429 rate limit exceeded. You hit the 120 req/min cap. Wait 30 seconds (the Retry-After header tells you exactly) or raise RATE_LIMIT_PER_MIN in middleware.ts.

403 cross-origin request blocked. Mutating requests must be same-origin. If you legitimately need a different origin during dev, allow it in middleware.ts's sameOrigin check.


Curriculum highlights — internals you won't find in most courses

  • Tokenization — BPE / WordPiece / SentencePiece, byte-level encoding, why Arabic costs 3× more tokens than English of equal meaning.
  • Encoder forward pass — token embedding → positional info → N transformer blocks → pooling (CLS / mean / last-token / attention) → L2-normalize, with worked dimensions for BGE-M3.
  • Transformer architecturesoftmax(QK^T/√d_head)V from first principles, multi-head, GQA, FFN/SwiGLU, RoPE, RMSNorm, residual stream framing, KV cache memory math.
  • Inference internals — KV cache cost formula, PagedAttention, AWQ/GPTQ/GGUF quantization, speculative decoding (Medusa), TTFT vs TPOT.
  • HNSW internals — graph construction algorithm, neighbour-selection diversity heuristic, M/ef_construction/ef_search knobs, IVF-PQ contrast, ~50-line HNSW-from-scratch lab.

Author

Built by Mostafa Ayman (@mdSHash).


License

MIT — adapt freely.

mdSHash/NueralPath

AI Engineer Mastery Terminal — RAG, embeddings, LLMs, agents, production AI. Next.js 15 + TypeScript + Prisma + Gemini 3.1 Pro Preview.

0

stars

0

commits

TypeScript

primary language

Jun 2, 2026

updated

nueral-path.vercel.app

README

NeuralPath

NeuralPath

An engineering-terminal learning platform for senior AI engineers. Six modules · forty-eight lessons · interview simulator · AI-graded code labs.

▸ Live demo — nueral-path.vercel.app

Next.js TypeScript Tailwind Prisma Gemini Deployed on Vercel

Live demo · Features · Architecture · Quick start · API surface · Security


Why this exists

Most AI-engineering content stops at "what is RAG". NeuralPath goes the other way: production-grade trade-offs first, code labs that ask you to implement, an interview simulator that scores you on correctness, depth, and clarity, and an in-browser Python runtime so you actually run the code you write.

Built as a personal mastery tool for top-tier AI engineer interviews while working on production AI systems at IBM. Single-user, local-first, deployable to a free Vercel + Neon stack in under three minutes.

The aesthetic is intentional — deep charcoal, electric cyan, terminal-grid backgrounds. Bloomberg meets sci-fi mission control, not another purple-gradient AI dashboard.


Features

48 lessons across 6 modulesRAG (naïve → CRAG → eval), embeddings (with tokenization + transformer forward-pass internals), LLM models (transformer architecture + inference internals), agents, production AI (with HNSW internals), enterprise patterns. Each lesson: theory body, animated diagram, decision card, interview gotchas, scored quiz.
Three-mode hands-on labsWalkthrough reveals code section by section with key-points and "what to notice" callouts. Practice gives you starter-code stubs and AI-graded verification. Experiment is a free Monaco editor with a Gemini code-explainer. Optional Pyodide Web Worker actually runs your Python in the browser.
Interview simulatorConceptual / system-design / coding / behavioral modes × three difficulties × three company types. Each answer scored on correctness, depth, and clarity, with a written critique and ideal answer. Sessions persist; history feeds the readiness score.
AI tutor chatStreaming responses, lesson-aware context, persistent history.
Animated SVG diagramsRAG pipeline, embedding space, chunking comparison, model decision tree, agent loop, LangGraph state machine, hybrid-search RRF, RAGAS eval radar.
Concept glossary~130 terms with high/medium/low frequency badges, lesson cross-links, and on-demand Gemini "Simplify" explanations.
Progress telemetryRecharts module-mastery bar chart, score-trajectory line chart with 5-session moving average, quiz-score scatter, recent-sessions log.

Tech stack

LayerChoiceWhy
FrameworkNext.js 15 App RouterRSC + streaming for the tutor; Node runtime for API routes; built-in middleware for CSRF + rate limit
LanguageTypeScript strict modeType safety from prompt schemas to UI
StylingTailwind CSS 3.4Custom dark engineering-terminal tokens
MotionFramer Motion 11Page transitions, diagram animations, panel reveals
EditorMonaco (@monaco-editor/react)Same editor as VS Code; lazy-loaded
Python runtimePyodide 0.26Real CPython + NumPy in a Web Worker
ChartsRechartsDark-themed analytics
ORM / DBPrisma 5 + Postgres (Neon)Single schema swaps to SQLite for local dev
LLM@google/generative-ai · gemini-3.1-pro-previewServer-side only — key never reaches the browser
ValidationZodPer-route request schemas + env validation
Markdownreact-markdown + remark-gfmNo dangerouslySetInnerHTML anywhere

Architecture

┌────────────────────────────────────────────────────────────────┐
│  Browser                                                       │
│  • App Router pages (RSC) — dashboard, lessons, glossary,      │
│    progress, interview, tutor, playground                      │
│  • Client islands — Monaco, Recharts, Framer Motion, streaming │
│    chat, Pyodide Web Worker                                    │
└──────────────────────────┬─────────────────────────────────────┘
                           │  fetch (same-origin, rate-limited)
┌──────────────────────────▼─────────────────────────────────────┐
│  middleware.ts                                                 │
│  • per-IP token-bucket rate limit (120 req/min)                │
│  • same-origin enforcement on POST/PUT/PATCH/DELETE            │
└──────────────────────────┬─────────────────────────────────────┘
                           │
┌──────────────────────────▼─────────────────────────────────────┐
│  Next.js 15 — Node runtime API routes                          │
│                                                                │
│  /api/health              env + db probe                       │
│  /api/chat                streaming Gemini tutor               │
│  /api/interview/*         session, generate, evaluate, log     │
│  /api/explain             code walkthrough on demand           │
│  /api/walkthrough         lab walkthrough generation           │
│  /api/verify              AI-graded lab task verification      │
│  /api/simplify            ELI-junior helper                    │
│  /api/harder              escalate interview question          │
│  /api/progress            lesson progress + readiness          │
│  /api/note                per-lesson notes                     │
│                                                                │
│  Each route:                                                   │
│    • validates input via Zod (lib/validation.ts)               │
│    • wraps Gemini calls in retry-with-backoff (lib/retry.ts)   │
│    • emits structured JSON logs (lib/logger.ts)                │
└──────────┬─────────────────────────────────────────┬───────────┘
           │                                         │
   ┌───────▼─────────┐                       ┌───────▼─────────┐
   │  Prisma · Neon  │                       │  Gemini API     │
   │  Postgres       │                       │  3.1 Pro        │
   │                 │                       │  preview        │
   │  Users          │                       │                 │
   │  LessonProgress │                       │  Server-side    │
   │  InterviewSession                       │  only — key     │
   │  InterviewQuestion                      │  never reaches  │
   │  CodeSubmission │                       │  the browser    │
   │  Note · Badge   │                       └─────────────────┘
   │  ChatMessage    │
   └─────────────────┘

Quick start

git clone git@github.com:mdSHash/NueralPath.git
cd NueralPath

# 1. install
npm install --legacy-peer-deps

# 2. configure
cp .env.example .env
# then edit .env and set GEMINI_API_KEY + DATABASE_URL

# 3. database
npm run db:push     # creates the schema in your Postgres
npm run db:seed     # creates the default user

# 4. dev server
npm run dev

Open http://localhost:3000.

For local development without Postgres, flip provider = "sqlite" in prisma/schema.prisma and use DATABASE_URL=file:./dev.db.


Deploy your own

Cloning to a fresh stack takes about three minutes:

Deploy with Vercel

  1. Click the button above (or import mdSHash/NueralPath in the Vercel dashboard).
  2. Provision a free Postgres at neon.tech and copy the pooled connection string.
  3. Set Vercel env vars:
    • GEMINI_API_KEY — from Google AI Studio
    • DATABASE_URL — your Neon pooled URL
  4. Deploy. Vercel runs npm run vercel-build, which regenerates the Prisma client, pushes the schema, and builds Next.js — the database is initialised automatically.
  5. Hit <your-url>/api/health to verify.

Curriculum

#ModuleFocusLessons
1RAGNaive → Advanced → Modular → Agentic → GraphRAG → Multimodal → CRAG → Eval10
2EmbeddingsModels, chunking, vector DBs, hybrid search, multilingual, tokenization, encoder forward pass9
3LLM ModelsSelection, OS vs proprietary, watsonx, routing, transformer architecture, inference internals10
4Agents & OrchestrationReAct, LangGraph, multi-agent, tool design, memory, eval6
5Production AIObservability, evals, guardrails, latency, cost, CI/CD, HNSW internals8
6Enterprise / IBMMulti-tenant RAG, MQ integration, Azure OpenAI, responsible AI, ROI5

Each lesson includes: theory body (Markdown) · animated SVG diagram (where applicable) · key takeaways · decision card (when-to-use / not / trade-offs) · interview gotchas · scored quiz · optional code lab.


Project layout

app/
  page.tsx                     dashboard
  learn/                       curriculum index + lesson viewer
  playground/                  standalone Monaco labs
  interview/                   interview simulator
  chat/                        AI tutor
  glossary/                    searchable term dictionary
  progress/                    charts + recent sessions
  api/                         12 endpoints — Gemini + persistence + health
components/
  ui/                          design-system primitives
  layout/                      sidebar, topbar shell
  dashboard/                   hero, learning map, readiness, next lesson
  lesson/
    LessonClient.tsx           viewer shell
    KeyTakeaways · DecisionCard · Gotchas · Quiz · DiagramSlot
    lab/
      LabTabs.tsx              walkthrough / practice / experiment switch
      WalkthroughLab.tsx       sections with reveal pacing
      PracticeLab.tsx          editor + verify + reference solution
      ExperimentLab.tsx        free editor + AI explainer
      PyodideRunner.tsx        Web-Worker Python runtime panel
  interview/                   setup, runner, summary
  diagrams/                    eight animated SVG concept diagrams
hooks/
  usePyodide.ts                worker lifecycle + run helper
lib/
  curriculum/                  six module files + glossary + interview seed
  gemini.ts                    server-only SDK wrapper with retries
  env.ts                       Zod-validated process.env
  validation.ts                per-route + lab request schemas
  logger.ts                    structured JSON logger
  retry.ts                     exponential-backoff helper
  db.ts                        Prisma client singleton
public/
  pyodide-worker.js            Web Worker that hosts Pyodide
prisma/
  schema.prisma                Postgres schema
  seed.ts                      default user + starter progress
middleware.ts                  rate limit + same-origin enforcement
next.config.ts                 security headers + CSP

API surface

All routes live at /api/*, run on the Node runtime, validate request bodies with Zod, and emit structured logs on failure.

Method · RouteBody / paramsReturns
GET /api/health{ status, model, db, time }
POST /api/chat{ message, moduleId?, lessonId?, history? }streamed text/plain (Gemini tokens)
GET /api/chat{ messages[] } recent tutor history
POST /api/interview/session{ mode, companyType, role, difficulty, module? }{ sessionId }
GET /api/interview/session{ sessions[] }
POST /api/interview/generate{ mode, companyType, role, difficulty, module?, count? }{ questions[], source }
POST /api/interview/evaluate{ question, userAnswer, role, difficulty, mode }{ scoreCorrectness, scoreDepth, scoreClarity, feedback, idealAnswer, missingConcepts[] }
POST /api/interview/questionfull per-question record{ id }
POST /api/explain{ code, language? }{ explanation }
POST /api/walkthrough{ labTitle, language, starterCode, expectedConcepts? }{ sections[] }
POST /api/verify{ taskPrompt, taskDescription, language, userCode, referenceSolution? }{ passed, score, feedback, hints[] }
POST /api/simplify{ concept }{ explanation }
POST /api/harder{ question, mode? }{ question }
GET /api/progressaggregate readiness telemetry
POST /api/progress{ moduleId, lessonId, status?, quizScore?, addTime? }updated LessonProgress row
GET /api/note?moduleId&lessonId{ notes[] }
POST /api/note{ moduleId, lessonId, body }{ note }
DELETE /api/note{ id }{ ok }

Mutating routes require Origin === Host. Cross-origin → 403. Rate-limited at 120 req/min per IP.


Environment variables

NameRequiredDefaultPurpose
GEMINI_API_KEYyesServer-side Google Generative AI key. Never sent to the browser.
GEMINI_MODELnogemini-3.1-pro-previewOverride the model name.
DATABASE_URLyesPrisma datasource. Postgres connection string (Neon, Supabase, Vercel Postgres). For SQLite dev, set provider = "sqlite" in prisma/schema.prisma and use file:./dev.db.
NODE_ENVnodevelopmentproduction enables HSTS.

.env is gitignored. Use .env.example as the template and never commit a real key.


Security

The app ships the controls a public-facing Next.js app should have, even though it's designed for single-user use.

LayerControl
NetworkTLS-only via Vercel; HSTS in production builds (Strict-Transport-Security: max-age=63072000; includeSubDomains; preload)
BrowserStrict CSP (default-src 'self'; Gemini connect-src restricted), frame-ancestors 'none', X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Resource-Policy: same-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), X-Powered-By removed
Edgemiddleware.ts enforces same-origin on every mutating /api/* request and applies a per-IP token bucket (120 req/min)
AppZod request-body validation on every API route; Zod-validated process.env at startup; exponential-backoff retry around every Gemini call; structured JSON logging
DataPrisma parameterised queries throughout; no raw SQL; react-markdown + remark-gfm everywhere — no dangerouslySetInnerHTML
SecretsGemini SDK imported only inside app/api/** and lib/gemini.ts; no NEXT_PUBLIC_* keys; .env gitignored
Runtime isolationPyodide runs inside a Web Worker, sandboxed away from the main thread

npm audit is clean against direct dependencies. Next.js is pinned to 15.5.19+ which patches the critical RCE in the React Flight protocol (GHSA-9qr9-h5gf-34mp) and the middleware authorization-bypass (GHSA-f82v-jwr5-mffw) that affected earlier 15.x.

Out of scope

  • Authentication. Single-user app; default user user_default is auto-created. To go multi-tenant: add NextAuth, key Prisma queries on session.user.id, tighten the CSRF check.
  • Distributed rate limiting. Token bucket lives in process memory. For multi-instance deploys swap to Upstash Ratelimit; the middleware shape stays the same.

Scripts

ScriptWhat it does
npm run devNext.js dev server on :3000
npm run buildProduction build (no DB migration — for local builds)
npm run vercel-buildWhat Vercel runs: prisma generate && prisma db push --accept-data-loss && next build
npm run startStart the production build
npm run lintESLint via next lint
npm run db:pushPush the Prisma schema to your DB
npm run db:generateRegenerate the Prisma client
npm run db:seedSeed the default user + starter progress

Troubleshooting

Could not resolve dependency on npm install. Some peers want React 19. Rerun with npm install --legacy-peer-deps.

/api/health returns db: "fail". Prisma can't reach your DB. Check DATABASE_URL. For Neon, use the pooled connection string (the URL with -pooler in the host).

Chat / interview / explain returns 502. Either GEMINI_API_KEY is missing or the model returned an error. Check the dev-server console — lib/logger.ts emits a structured line with the failing route.

Monaco fails to load. Loaded via next/dynamic with ssr: false. Ensure JavaScript is enabled and the CSP shipped here isn't being overridden by your platform.

Pyodide takes 10–20 s to start. Expected on first use — it downloads ~10 MB from cdn.jsdelivr.net and initialises a Web Worker. Subsequent runs are instant.

429 rate limit exceeded. You hit the 120 req/min cap. Wait 30 seconds (the Retry-After header tells you exactly) or raise RATE_LIMIT_PER_MIN in middleware.ts.

403 cross-origin request blocked. Mutating requests must be same-origin. If you legitimately need a different origin during dev, allow it in middleware.ts's sameOrigin check.


Curriculum highlights — internals you won't find in most courses

  • Tokenization — BPE / WordPiece / SentencePiece, byte-level encoding, why Arabic costs 3× more tokens than English of equal meaning.
  • Encoder forward pass — token embedding → positional info → N transformer blocks → pooling (CLS / mean / last-token / attention) → L2-normalize, with worked dimensions for BGE-M3.
  • Transformer architecturesoftmax(QK^T/√d_head)V from first principles, multi-head, GQA, FFN/SwiGLU, RoPE, RMSNorm, residual stream framing, KV cache memory math.
  • Inference internals — KV cache cost formula, PagedAttention, AWQ/GPTQ/GGUF quantization, speculative decoding (Medusa), TTFT vs TPOT.
  • HNSW internals — graph construction algorithm, neighbour-selection diversity heuristic, M/ef_construction/ef_search knobs, IVF-PQ contrast, ~50-line HNSW-from-scratch lab.

Author

Built by Mostafa Ayman (@mdSHash).


License

MIT — adapt freely.

Languages

TypeScript

99.1%