BookExchange (The Story)


Inspiration

It started at the university library.

You borrowed or bought a book for a week. You finish it in two days. For the next five days, the book sits on your desk, unavailable to every other student who might need it. Now imagine that happening across the entire campus. Multiply it by hundreds of students, and you get a library where books are technically "checked out" but not actually being read.

The problem gets worse with limited-copy titles. Take something like The AI Classroom: The Ultimate Guide to Artificial Intelligence in Education by Daniel Fitzpatrick, Amanda Fox, and Brad Weinstein, if the library only has 3 copies and all three are borrowed by students who finished reading days ago, every other student who wants that book is stuck waiting. Not because the books are being used, but because the library's fixed return cycle doesn't account for how fast you actually read.

We saw this play out constantly. A student finishes a book in 2 days but holds it for the full week. Meanwhile, another student desperately needs the same book for an assignment or just wants to continue reading a series, and they can't get it. The books exist, the readers are done, but there's no bridge between them.

Beyond the library, the problem extends to textbooks and reference materials that are expensive, used for one semester, and then forgotten. Students who can't afford new books have no structured way to find someone who's done with theirs.

This personal experience inspired us to build BookExchange, a platform where students can exchange books directly, so a book you're done with reaches the next reader immediately, without waiting for the library return cycle. If the book is bought, the ownership changes; if the book is borrowed, the library will be informed, and the one who now has the ownership will return the book to the library.

The idea was simple: if you've finished reading, someone else shouldn't have to wait.

The Problem

University libraries operate on fixed borrowing periods typically one to two weeks per book. Students frequently finish reading well before the due date, yet the book remains checked out and inaccessible to others for the full borrowing window.

For titles with limited copies, this creates artificial scarcity: all available copies may be held by students who have already finished reading, while others who need the same book are forced to wait not because the books are unavailable, but because the system doesn't account for actual reading time.

Beyond the library:

  • Financial burden - textbooks and reference materials are expensive, and many students cannot afford to purchase them every semester
  • Wasted resources - a large number of books remain unused after a semester, sitting on shelves with no structured way to reach students who need them
  • No peer-to-peer system - there is no centralized, student-friendly platform that enables direct exchange of academic materials within educational communities
  • Artificial scarcity - popular and limited-copy titles remain locked in the library's rigid borrowing timeline, even when current holders have finished reading
  • Inefficient circulation - books move through the system far slower than students actually read them

What It Does

To address this problem, we developed BookExchange - a platform built around the university library experience that allows students to exchange books directly with each other using a point-based system.

The core idea: if you finish a library book early, you can list it on the platform and let another student acquire it through points, no money, no waiting for the library return cycle. The system connects students who have finished reading with those who need the same book right now, creating a collaborative ecosystem that works alongside the library, not as a replacement.

The Core Loop

  1. You sign up and get 1,000 points to start.
  2. You list a book you've finished reading, its condition, photos, your location. Our AI (Google Gemini) calculates the point value based on condition, how many copies exist in the system, and how many people are requesting similar books.
  3. Someone requests your book and spends points. You can accept, decline, or they can cancel.
  4. When you accept, points transfer automatically - the requester pays, you earn.
  5. Need more books but low on points? You can buy points via Stripe or list more books.

A Real Scenario

Ali borrows Brave New Words: How AI Will Revolutionize Education (and Why That's a Good Thing) by Sal Khan from the library for 1 week. He finishes it in 2 days. On Day 3, he lists it on BookExchange. Sara has been waiting for a copy, all 3 library copies are checked out. She sees Ali's listing, requests it for 150 points, and picks it up the same afternoon. Ali earns 150 points he can spend on his next read. Sara doesn't have to wait 5 more days for the library cycle. The book keeps moving.

Beyond Trading

  • AI Book Valuation & Recommendations - Gemini AI calculates fair point values based on condition, rarity, and demand. It also analyzes your library to suggest personalized book matches.
  • BookBot Assistant - a floating AI chatbot on every page that helps you discover books, answers platform questions, and suggests exchanges based on your reading taste.
  • Real-Time Chat - direct messaging tied to specific books, powered by Pusher. Live notifications and unread counts keep conversations flowing.
  • Exchange Map - physical exchange stall locations pinned on an interactive Leaflet map. Register your own campus spot or find someone nearby for in-person handoffs.
  • QR-Based Book Journey Tracking - every book gets a unique digital ID. Scan the QR code and see the book's full journey, who read it, where, how long, their notes, tips for the next reader, and ratings. The history survives even if users delete their accounts.
  • AI Reading Insights - AI analyzes your reading history and generates a personality profile: favorite genres, reading pace, personality traits, and fun facts.
  • Community Forums - category-based discussions (chapter debates, book reviews, recommendations) with threaded replies, reactions, anonymous posting, and moderation.

How We Built It

The project is a Next.js 16 app (App Router) with React 19 and TypeScript throughout.

API Layer: We used tRPC v11 for the entire API — 8 router modules (book, exchange, forum, chat, bookBot, bookHistory, readingInsights, testing). Every call is end-to-end typesafe, validated with Zod v4, and cached/refetched through TanStack React Query on the client.

Database: MongoDB via Prisma v6 ORM. We ended up with 16 models across 6 domains — users/auth, book exchange, forums, messaging, physical stalls, and book history. Every model has strategic indexes for the queries we actually run.

AI Integration: Google Gemini handles 5 distinct features:

  • Book valuation (with a rule-based fallback if the API fails)
  • Personalized recommendations based on your library and request history
  • The BookBot chatbot
  • Reading insights personality analysis
  • Reading time estimation from book metadata

We built the valuation with a dual approach, Gemini generates a point value with reasoning, but if the API response is unparseable or out of range (50–500 points), a fallback algorithm kicks in using condition multipliers, rarity factors, and demand multipliers. We didn't want a broken AI call to block someone from listing a book.

Auth: Better Auth handles email/password (with email verification via Brevo SMTP), Google OAuth, and GitHub OAuth. The middleware fetches the session on every route and enforces authentication and email verification.

Real-Time: Pusher for WebSocket-based live chat and notification delivery. Messages are sent server-side and received client-side via pusher-js.

Frontend: Tailwind CSS v4 for styling, Framer Motion and GSAP for animations (the landing page has scroll-driven parallax, reveal animations, and floating elements). Leaflet + React-Leaflet for the exchange stall map. Cloudinary for image uploads.

Payments: Stripe Checkout Sessions for buying points, with a webhook endpoint that listens for checkout.session.completed events and credits the user's balance.


Challenges We Ran Into

Getting the AI valuation right. Early on, Gemini would return wildly inconsistent point values, sometimes 10, sometimes 2000. We had to carefully engineer the prompt, enforce a strict JSON response format, validate the output range, and build the entire fallback calculation system. Parsing Gemini's response reliably (extracting JSON from text that sometimes includes markdown fences) was more annoying than expected.

The points economy balance. If listing a book gives you too many points, everyone lists junk. If requesting costs too much, nobody exchanges. We iterated on the multipliers (condition, rarity, demand) multiple times. The rarity system — counting how many copies of a similar book exist in the system — was a late addition that made the economy feel much fairer.

Real-time chat at scale. Conversations are scoped to a specific book and two participants. The tricky part was the "get or create" pattern, checking if a conversation already exists between two users for a specific book, handling the bidirectional participant lookup (participant1/participant2 in either order), and keeping the unread counts accurate across both WebSocket events and database reads.

Preserving book history when users are deleted. The BookHistoryEntry model deliberately stores reader name and avatar as denormalized fields (not just a foreign key). When a user deletes their account, their reading entries survive because the data is already embedded. Getting this right meant we couldn't just onDelete: Cascade everything.

Middleware complexity. The auth middleware has to handle multiple edge cases: unauthenticated users on protected routes, authenticated users on auth pages, verified vs. unverified users, and the reset-password page (which should be accessible even when logged in). Getting every redirect chain correct without loops took careful testing.

Forum moderation. Building the reaction system with unique constraints per user (you can only "Like" a discussion once, but you can also "Helpful" it) required composite unique indexes. The report workflow (Pending → Reviewed → Action Taken / Dismissed) added another state machine on top of the request status workflow.


Accomplishments That We're Proud Of

  • The AI valuation actually works. Books get fair, contextual pricing, a rare, high-demand book in perfect condition genuinely costs more points than a common, beat-up paperback. And it degrades gracefully when the API is unavailable.

  • The book journey feature. Scanning a QR code and seeing a book's path across 4 readers in 3 different cities, with their notes and tips — that's the feature that makes people go "wait, that's actually cool." History surviving user deletion was a deliberate design choice we're glad we made.

  • End-to-end type safety. From the Prisma schema → tRPC routers → React components, there's a single source of truth. A schema change in Prisma surfaces type errors all the way to the frontend. Zero runtime type mismatches.

  • The dual valuation system. AI-first with a deterministic fallback. No single point of failure in the points economy.

  • Solving a real problem we actually had. This isn't a hypothetical product. We built it because we lived the frustration of waiting for library books that were already finished being read. That authenticity drove every design decision.


What We Learned

  • Prompt engineering is software engineering. Crafting Gemini prompts that return parseable, consistent, bounded results required the same rigor as writing business logic. You can't trust the output, you validate, constrain, and build fallbacks.

  • Points economies are game design. Balancing earn rates vs. spend rates vs. Stripe pricing is an incentive design problem, not just a database problem. Small changes to multipliers have big behavioral effects.

  • tRPC is a productivity multiplier. Once the router structure is set up, adding a new endpoint is almost trivial, define the input schema, write the logic, and the client types are already there. No manual API contracts.

  • Denormalization is a feature, not a smell. Storing reader names directly in history entries (instead of just user IDs) was the right call for data that needs to outlive user accounts.

  • Middleware deserves its own test suite. Auth redirect logic with 5+ conditional branches is a bug factory if you don't enumerate every case.

  • Real-time is easy to add, hard to get right. Pusher makes message delivery trivial, but keeping unread counts, conversation ordering, and notification state consistent across live updates and page reloads is where the real work is.


What's Next for BookExchange

  • University library integration - partner with campus libraries to show real-time availability alongside peer listings, and auto-suggest exchanges when a library copy is unavailable.
  • Mobile app - React Native or a progressive web app for on-the-go exchanges.
  • Expanded AI - book condition detection from photos, automated description generation, and smarter recommendation algorithms that factor in reading speed and genre preferences.
  • University partnerships - campus-specific instances with verified .edu email domains and curated exchange stalls at libraries and common areas.
  • Gamification - reading streaks, badges for books exchanged, leaderboards, and seasonal challenges.
  • Advanced moderation - AI-assisted content moderation for forums and chat, automated flagging of suspicious exchange patterns.
  • Multi-language support - i18n for the platform, and language-aware book recommendations.
  • Sustainability dashboard - track collective impact: books exchanged, estimated CO₂ saved, trees preserved.

The long-term vision: make BookExchange the layer that sits on top of every university library, where the moment you finish a book, the next reader is already waiting. No book sits idle. No student waits unnecessarily. Every story keeps moving.


Team Information

Kaleemullah Younas

  • Role: Full-Stack AI Engineer - GITHUB

Muhammad Umer

  • Role: Web Developer & Devops - GITHUB

Contact

  • Primary Contact Email: EMAIL

Built With

Share this project:

Updates