WS 101 study hub

WS 101 · Pre-final · Module 7 · ~75–90 min

Student Marketplace → Real Data

Replace the fake array with Neon + Prisma. Post a listing, refresh — it is still there.

Your progress

0 / 10

Before you start

Check these off so you’re ready to save a real row.

Not today

Do not add Cloudinary, Vercel, or login. Never commit .env or paste the Neon connection string in chat.

STEP 1

Neon + Prisma 6 + Listing table

  1. 1

    Create a Neon project named marketplace and copy the postgresql:// connection string.

  2. 2

    In your Next.js app run npm install prisma@6 @prisma/client@6 then npx prisma init. Use version 6 — latest Prisma needs extra files we skip in class.

  3. 3

    Put the string in .env as DATABASE_URL="...".

  4. 4

    Add the Listing model, then run npx prisma migrate dev --name init and npx prisma studio.

prisma/schema.prismafull schema
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Listing {
  id          Int      @id @default(autoincrement())
  title       String
  description String
  price       Float
  imageUrl    String   @default("https://placehold.co/300x200")
  createdAt   DateTime @default(now())
}

Prisma Studio should open an empty Listing table. Empty is success. If you see prisma.config.ts or adapter errors, reinstall Prisma 6.

STEP 2

GET and POST at /api/listings

  1. 1

    Create lib/db.ts with one PrismaClient. Import this file everywhere you need the database.

  2. 2

    Create app/api/listings/route.ts (not route.js).

  3. 3

    Export GET that findMany newest first, and POST that creates from the JSON body.

  4. 4

    Open http://localhost:3000/api/listings — you should see JSON, not the homepage.

lib/db.ts + app/api/listings/route.tsGET reads · POST writes
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default prisma;

// route.ts
import prisma from '@/lib/db';

export async function GET() {
  const listings = await prisma.listing.findMany({
    orderBy: { createdAt: 'desc' },
  });
  return Response.json(listings);
}

export async function POST(request: Request) {
  const body = await request.json();
  const listing = await prisma.listing.create({
    data: {
      title: body.title,
      description: body.description,
      price: parseFloat(body.price),
    },
  });
  return Response.json(listing);
}
browser consoleoptional test POST
fetch('/api/listings', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: 'Test Item',
    description: 'A test.',
    price: 100,
  }),
})

An empty array [] means the route works and the table is still empty.

STEP 3

Home reads the table

  1. 1

    Remove the hard-coded listings array from app/page.tsx.

  2. 2

    Make Home an async function and load listings with prisma.listing.findMany.

  3. 3

    Keep Module 6 ListingCard and Link.

  4. 4

    Add a link to /post.

app/page.tsxno fake array
import ListingCard from '../components/ListingCard';
import Link from 'next/link';
import prisma from '@/lib/db';

export default async function Home() {
  const listings = await prisma.listing.findMany({
    orderBy: { createdAt: 'desc' },
  });

  return (
    <main style={{ padding: '32px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '24px' }}>
        <h2>Available Listings</h2>
        <Link href="/post">Post an Item</Link>
      </div>
      <div style={{ display: 'flex', gap: '24px', flexWrap: 'wrap' }}>
        {listings.map((item) => (
          <Link key={item.id} href={'/listings/' + item.id}>
            <ListingCard title={item.title} price={item.price} description={item.description} />
          </Link>
        ))}
      </div>
    </main>
  );
}

The home page reads the table. The form writes through the API. Same database.

STEP 4

Post form + detail page

  1. 1

    Create app/post/page.tsx with 'use client' at the top.

  2. 2

    Use useState for title, price, and description — this page runs in the browser so inputs can remember text.

  3. 3

    On submit, POST /api/listings then router.push('/').

  4. 4

    Update app/listings/[id]/page.tsx to findUnique after await params — database ids are not the old 1, 2, 3.

app/post/page.tsxuse client · POST
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function PostItem() {
  const [title, setTitle] = useState('');
  const [price, setPrice] = useState('');
  const [description, setDescription] = useState('');
  const router = useRouter();

  async function handleSubmit(e) {
    e.preventDefault();
    await fetch('/api/listings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title, price, description }),
    });
    router.push('/');
  }

  return (
    <main style={{ padding: '32px', maxWidth: '500px' }}>
      <h2>Post an Item</h2>
      <form onSubmit={handleSubmit}>
        <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" required />
        <input type="number" value={price} onChange={(e) => setPrice(e.target.value)} placeholder="Price" required />
        <textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Description" required />
        <button type="submit">Post Item</button>
      </form>
    </main>
  );
}
app/listings/[id]/page.tsxfindUnique
import prisma from '@/lib/db';

export default async function ListingDetail({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const listing = await prisma.listing.findUnique({
    where: { id: parseInt(id) },
  });

  if (!listing) {
    return <p style={{ padding: '32px' }}>Listing not found.</p>;
  }

  return (
    <main style={{ padding: '32px' }}>
      <h1>{listing.title}</h1>
      <p>₱{listing.price}</p>
      <p>{listing.description}</p>
    </main>
  );
}

Post through the form. Refresh home. The listing stays. That is Wall 1, gone.

STEP 5

Seed sample listings

  1. 1

    Download seed.ts and save it as prisma/seed.ts.

  2. 2

    In the project folder run npx tsx prisma/seed.ts.

  3. 3

    Refresh home — six campus sample listings should appear.

  4. 4

    Optional: open Prisma Studio and confirm the same six rows.

terminalafter saving prisma/seed.ts
npx tsx prisma/seed.ts

# Expected:
# Seeding sample marketplace listings...
# Done. 6 listings ready — refresh your home page.

Seed clears existing Listing rows first (deleteMany), then inserts six samples. Post your own after seeding.

Done checklist

Tick everything before you submit.

Submit

Turn in the repo (no .env) and two screenshots that prove the row survived a refresh.

DeliverableWhat to turn in
RepoGitHub URL — without .env
HomeScreenshot after refresh, showing a listing you posted
StudioScreenshot of that row in Prisma Studio

Still on a fake array? Finish Module 6 first then come back. Photos and a live URL are Pre-final Module 8 .