React: Comprehensive Hands-On Exercise

Last updated: 2026-08-26

This lesson is the final installment of our 30-lesson React tutorial series. You’ll apply all the knowledge you’ve learned so far—Next.js App Router, data fetching, UI component libraries, authentication and authorization, and CI/CD deployment—to build a multi-tenant SaaS Kanban application from scratch. This isn’t just a demo project; it’s a real product ready for deployment and operation.


1. Project Overview

(1) Feature Description

SaaS Kanban is a lightweight project management tool designed for teams. Its core features include:

Functional Module Description Related Technologies
Dashboard Panel Drag and drop cards between columns @dnd-kit Drag-and-Drop Library
Task Management Create/Edit/Delete/Assign Tasks Server Action + Database
Multi-tenant Separate workspaces for each team Tenant ID data isolation
User Authentication Email and Password Login + Google OAuth NextAuth.js
Real-time updates Automatically syncs to the servidor after dragging Server Action optimistic update
Data Statistics Kanban Status Bar Chart Recharts Chart Library
Deployment Automated CI/CD Pipeline Vercel + GitHub Actions

(2) Technical Architecture

TEXT 📖 Display only
Project Root Directory/
├── app/                    # App Router Routing
│   ├── (auth)/             # Pages Related to Certification
│   │   ├── login/          # Login Page
│   │   ├── register/       # Registration Page
│   │   └── layout.tsx      # Authentication Page Layout
│   ├── (dashboard)/        # Dashboard(You must log in)
│   │   ├── board/          # Kanban Page
│   │   │   ├── [id]/       # Specific Kanban Board
│   │   │   └── page.tsx    # List of Kanban Boards
│   │   ├── layout.tsx      # Dashboard Layout(Sidebar)
│   │   └── page.tsx        # Homepage Redirect
│   ├── api/                # Route Handler
│   │   ├── auth/           # NextAuth API
│   │   └── boards/         # Dashboard Data API
│   └── layout.tsx          # Global Layout
├── components/             # Reusable Components
│   ├── board/              # Kanban Component
│   ├── ui/                 # UI General Components
│   └── providers.tsx       # Ant Design Provider
├── lib/                    # Utility Functions
│   ├── prisma.ts           # Database Client
│   └── auth.ts             # NextAuth Layout
├── prisma/                 # Database Schema
│   └── schema.prisma
├── middleware.ts           # Route Guard
├── next.config.ts
└── package.json


2. Technical Architecture Diagram

Architecture Layer Technology Responsibilities
Front-end Presentation Layer Next.js + Ant Design SSR/SSG, UI Components, Interaction Logic
API Layer Route Handler + Server Action Data Interfaces, Business Logic, Form Submissions
Data Access Layer Prisma ORM Type-safe database queries
Storage Layer PostgreSQL Persistent Data Storage
Authentication Layer NextAuth.js Email and Password + Google OAuth
Deployment Layer Vercel + GitHub Actions CI/CD Automated Deployment

The overall architecture of SaaS Kanban consists of four layers: the front-end presentation layer (Next.js + Ant Design), the API layer (Route Handler + Server Action), the data access layer (Prisma ORM), and the storage layer (PostgreSQL). Authentication is centrally managed using NextAuth.js, and deployment is automated via Vercel + GitHub Actions.

100%
flowchart TD
    A[Browser] --> B[Next.js App]
    B --> C{Route Distribution}
    C -->|Public Routing| D[Log In/Register]
    C -->|Protected Routes| E[Kanban Page]
    E --> F[Server Component<br/>Data Collection]
    E --> G[Client Component<br/>Drag-and-Drop Interaction]
    F --> H[Prisma ORM]
    G --> I[Server Action<br/>Operation Synchronization]
    H --> J[(PostgreSQL)]
    I --> J
    D --> K[NextAuth.js]
    K --> J
    B --> L[Middleware]
    L -->|Not logged in| D
    L -->|Logged in| E
    B --> M[Vercel Deployment]
    M --> N[GitHub Actions CI/CD]


3. Project Setup and Database Design

(1) Initialize the project

BASH
# Create Next.js Project
npx create-next-app@latest saas-kanban --typescript --tailwind --app

# Install Core Dependencies
cd saas-kanban

# UI Component Library
npm install antd @ant-design/icons

# Drag-and-drop feature
npm install @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities

# Certification
npm install next-auth @auth/prisma-adapter

# Database
npm install prisma @prisma/client
npx prisma init

# Charts
npm install recharts

(2) Database Schema

Data Model Key Fields Relationships Description
User email, name, image → Board[], Task[] A user has multiple boards and tasks
Board title, description → Column[] Kanban has multiple columns
Column title, position → Task[] The column contains multiple task cards
Task title, priority, dueDate → User (assignee) Tasks can be assigned to users
Account/Session provider, token → User NextAuth auth required
PRISMA
// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

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

// User Model
model User {
  id            String    @id @default(cuid())
  name          String?
  email         String    @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  boards        Board[]   // User-Created Kanban Boards
  tasks         Task[]    // Tasks Assigned to Users
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
}

// Kanban Model(Multi-tenancy achieves data isolation by associating tenants with users.)
model Board {
  id        String   @id @default(cuid())
  title     String
  color     String   @default("#1677ff")
  ownerId   String
  owner     User     @relation(fields: [ownerId], references: [id])
  columns   Column[]
  tasks     Task[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

// Kanban Column
model Column {
  id        String @id @default(cuid())
  title     String
  position  Int    // Sort Order
  boardId   String
  board     Board  @relation(fields: [boardId], references: [id], onDelete: Cascade)
  tasks     Task[]
}

// Task Cards
model Task {
  id          String   @id @default(cuid())
  title       String
  description String?
  priority    Priority @default(middle)
  assigneeId  String?
  assignee    User?    @relation(fields: [assigneeId], references: [id])
  columnId    String
  column      Column   @relation(fields: [columnId], references: [id], onDelete: Cascade)
  boardId     String
  board       Board    @relation(fields: [boardId], references: [id], onDelete: Cascade)
  position    Int      // Sort Order Within a Row
  dueDate     DateTime?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

enum Priority {
  urgent
  high
  middle
  low
}

▶ Example 1: NextAuth.js Authentication Configuration

Output:

TEXT 📖 Display only
Project Root Directory/
TS
// lib/auth.ts - NextAuth Complete Configuration
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import CredentialsProvider from 'next-auth/providers/credentials'
import { PrismaAdapter } from '@auth/prisma-adapter'
import { prisma } from './prisma'

function verifyPassword(plain: string, hashed: string): boolean {
  // Production: use bcryptjs — npm i bcryptjs → bcrypt.compare(plain, hashed)
  return plain === hashed
}

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    // Google OAuth
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    // Log in with your email and password
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) return null

        const user = await prisma.user.findUnique({
          where: { email: credentials.email as string }
        })

        if (!user || !user.password) return null

        const isValid = verifyPassword(
          credentials.password as string,
          user.password
        )

        if (!isValid) return null
        return user
      },
    }),
  ],
  pages: {
    signIn: '/login',
    error: '/login',
  },
  callbacks: {
    // Add users ID Injecting Tenant Information JWT
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id
      }
      return token
    },
    // Inject JWT info into session
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id as string
      }
      return session
    },
  },
  session: {
    strategy: 'jwt',
  },
})

// lib/prisma.ts - Database Client Singleton
import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

Output:

TEXT 📖 Display only
NEXT_PUBLIC_API_URL → exposed to browser. API_SECRET → server-only. .env.local for local dev, .env.production for deploy.


4. Step-by-Step Coding

Below, we’ll implement the core code for the Kanban application step by step, organized by functional modules. Each step corresponds to a complete functional block; you can copy them into your project in order and run them.

(1) Kanban Page Layout and Data Retrieval

The core structure of the Kanban page is a "three-column layout": the left sidebar (Kanban list) and the central main area (column headers + task cards). This is a typical Server Component + Client Component hierarchy: the outer-layer Server Component retrieves Kanban data, while the inner-layer Client Component handles drag-and-drop interactions.

▶ Example 2: Retrieving Data from the Kanban Page Server Component

Output:

TEXT 📖 Display only
Async data fetching/loading states
TSX
// app/(dashboard)/board/[id]/page.tsx
// Server Component:Get kanban board, columns, task data
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { redirect } from 'next/navigation'
import BoardClient from './BoardClient'

interface BoardPageProps {
  params: { id: string }
}

async function BoardPage({ params }: BoardPageProps) {
  const session = await auth()
  // Redirect for Unauthenticated Users
  if (!session?.user?.id) redirect('/login')

  // Retrieve Kanban Data(Lists and Tasks)
  const board = await prisma.board.findUnique({
    where: {
      id: params.id,
      ownerId: session.user.id, // Multi-tenant Data Isolation
    },
    include: {
      columns: {
        orderBy: { position: 'asc' },
        include: {
          tasks: {
            orderBy: { position: 'asc' },
            include: { assignee: { select: { id: true, name: true, image: true } } },
          },
        },
      },
    },
  })

  if (!board) redirect('/board')

  // Serialization Date Field(Server Component Forwarded to Client Component When needed)
  const serializedBoard = JSON.parse(JSON.stringify(board))

  return <BoardClient board={serializedBoard} />
}
export default BoardPage

// app/(dashboard)/board/[id]/BoardClient.tsx
// Client Component:Core of Drag-and-Drop Interaction
'use client'
import { useState, useCallback } from 'react'
import { DndContext, DragOverlay, closestCorners, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { Layout } from 'antd'
import BoardColumn from './BoardColumn'
import TaskCard from './TaskCard'

const { Content } = Layout

interface BoardData {
  id: string
  title: string
  columns: ColumnData[]
}

interface ColumnData {
  id: string
  title: string
  tasks: TaskData[]
}

interface TaskData {
  id: string
  title: string
  description?: string
  priority: string
  position: number
  assignee?: { id: string; name: string; image?: string }
}

function BoardClient({ board }: { board: BoardData }) {
  const [activeTask, setActiveTask] = useState<TaskData | null>(null)
  const [columns, setColumns] = useState(board.columns)

  // Configure Sensors(Pointer + Keyboard)
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(KeyboardSensor)
  )

  // Drag to Start:Record tasks that have been dragged
  const handleDragStart = useCallback((event: any) => {
    const { active } = event
    const task = columns
      .flatMap(col => col.tasks)
      .find(t => t.id === active.id)
    setActiveTask(task || null)
  }, [columns])

  // Drag ended:Update the "Assigned To" column and sort order
  const handleDragEnd = useCallback(async (event: any) => {
    const { active, over } = event
    if (!over || active.id === over.id) {
      setActiveTask(null)
      return
    }

    const sourceColumn = columns.find(col =>
      col.tasks.some(t => t.id === active.id)
    )
    const targetColumn = columns.find(col =>
      col.tasks.some(t => t.id === over.id) ||
      col.id === over.id
    )

    if (!sourceColumn || !targetColumn) {
      setActiveTask(null)
      return
    }

    const task = sourceColumn.tasks.find(t => t.id === active.id)!
    const newSourceTasks = sourceColumn.tasks.filter(t => t.id !== active.id)

    if (sourceColumn.id === targetColumn.id) {
      // Sort within the same column
      const overIndex = targetColumn.tasks.findIndex(t => t.id === over.id)
      const newTasks = [...newSourceTasks]
      newTasks.splice(overIndex, 0, task)
      setColumns(prev => prev.map(col =>
        col.id === sourceColumn.id ? { ...col, tasks: newTasks } : col
      ))
    } else {
      // Cross-Row Movement
      const overIndex = targetColumn.tasks.findIndex(t => t.id === over.id)
      const newTargetTasks = [...targetColumn.tasks]
      newTargetTasks.splice(overIndex, 0, task)
      setColumns(prev => prev.map(col => {
        if (col.id === sourceColumn.id) return { ...col, tasks: newSourceTasks }
        if (col.id === targetColumn.id) return { ...col, tasks: newTargetTasks }
        return col
      }))
    }

    // Sync to the server
    await fetch('/api/tasks/move', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        taskId: active.id,
        targetColumnId: targetColumn.id,
        position: targetColumn.tasks.findIndex(t => t.id === over.id),
      }),
    })

    setActiveTask(null)
  }, [columns])

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCorners}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      <Content style={{ display: 'flex', gap: 16, padding: 24, overflowX: 'auto' }}>
        {columns.map(column => (
          <BoardColumn key={column.id} column={column} />
        ))}
      </Content>
      <DragOverlay>
        {activeTask ? <TaskCard task={activeTask} isOverlay /> : null}
      </DragOverlay>
    </DndContext>
  )
}
export default BoardClient

Output:

TEXT 📖 Display only
TypeScript props: interface ButtonProps { text: string; onClick: () => void; color?: string }. Editor auto-completes, compile-time errors on misuse.

(2) Kanban Columns and Task Card Components

Each Kanban column is an independent component that includes a column header, a list of tasks, and a column color indicator. Task cards display the title, priority label, assignee’s avatar, and due date. Drag-and-drop functionality is implemented using the useSortable hook from @dnd-kit.

▶ Example 3: Column Components and Task Cards

Output:

TEXT 📖 Display only
State: activeTask (setter: setActiveTask), columns (setter: setColumns). useCallback memoizes handler. Async data fetching/loading states
TSX
// board/BoardColumn.tsx - Kanban Column Components
'use client'
import { useDroppable } from '@dnd-kit/core'
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { Card, Tag, Typography } from 'antd'
import TaskCard from './TaskCard'

const { Text } = Typography

interface ColumnProps {
  column: {
    id: string
    title: string
    tasks: any[]
  }
}

const columnColors: Record<string, string> = {
  'To-Do': '#f0f0f0',
  'In progress': '#e6f4ff',
  'Completed': '#f6ffed',
}

const columnHeaderColors: Record<string, string> = {
  'To-Do': '#d9d9d9',
  'In progress': '#1677ff',
  'Completed': '#52c41a',
}

function BoardColumn({ column }: ColumnProps) {
  // Set the placement area
  const { setNodeRef, isOver } = useDroppable({ id: column.id })

  return (
    <div
      ref={setNodeRef}
      style={{
        minWidth: 300,
        maxWidth: 360,
        flex: 1,
        background: isOver ? '#e6f4ff' : (columnColors[column.title] || '#fafafa'),
        borderRadius: 12,
        padding: 12,
        transition: 'background 0.2s',
      }}
    >
      {/* Column Headings */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <Text strong style={{ fontSize: 16 }}>
          {column.title}
        </Text>
        <Tag color={columnHeaderColors[column.title] || 'default'}>
          {column.tasks.length}
        </Tag>
      </div>

      {/* Sortable Task List */}
      <SortableContext items={column.tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minHeight: 100 }}>
          {column.tasks.map(task => (
            <TaskCard key={task.id} task={task} />
          ))}
        </div>
      </SortableContext>
    </div>
  )
}
export default BoardColumn

// board/TaskCard.tsx - Drag-and-drop task cards
'use client'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Card, Tag, Avatar, Typography, Tooltip } from 'antd'
import { CalendarOutlined } from '@ant-design/icons'

const { Text } = Typography

const priorityColors: Record<string, string> = {
  urgent: 'red',
  high: 'orange',
  middle: 'blue',
  low: 'green',
}

const priorityLabels: Record<string, string> = {
  urgent: 'Urgent',
  high: 'High',
  middle: 'in ',
  low: 'Low',
}

interface TaskCardProps {
  task: {
    id: string
    title: string
    description?: string
    priority: string
    dueDate?: string
    assignee?: { id: string; name: string; image?: string }
    position: number
  }
  isOverlay?: boolean
}

function TaskCard({ task, isOverlay }: TaskCardProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: task.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
    cursor: isOverlay ? 'grabbing' : 'grab',
  }

  return (
    <Card
      ref={setNodeRef}
      style={style}
      size="small"
      {...attributes}
      {...listeners}
      hoverable
      bodyStyle={{ padding: 12 }}
    >
      {/* Priority Labels */}
      <div style={{ marginBottom: 8 }}>
        <Tag color={priorityColors[task.priority]} style={{ fontSize: 11 }}>
          {priorityLabels[task.priority]}
        </Tag>
      </div>

      {/* Task Title */}
      <Text strong style={{ fontSize: 14, display: 'block', marginBottom: 4 }}>
        {task.title}
      </Text>

      {/* Task Description Preview */}
      {task.description && (
        <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 8 }}>
          {task.description.slice(0, 60)}...
        </Text>
      )}

      {/* Footer Information:Expiration Date + Person in Charge */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        {task.dueDate && (
          <Tooltip title={new Date(task.dueDate).toLocaleDateString('zh-CN')}>
            <Text type="secondary" style={{ fontSize: 11 }}>
              <CalendarOutlined /> {new Date(task.dueDate).toLocaleDateString('zh-CN')}
            </Text>
          </Tooltip>
        )}
        {task.assignee && (
          <Tooltip title={task.assignee.name}>
            <Avatar src={task.assignee.image} size={24}>
              {task.assignee.name?.[0]}
            </Avatar>
          </Tooltip>
        )}
      </div>
    </Card>
  )
}
export default TaskCard

// app/api/tasks/move/route.ts - Drag-and-Drop Synchronization API
import { prisma } from '@/lib/prisma'

export async function PUT(request: Request) {
  try {
    const { taskId, targetColumnId, position } = await request.json()

    // Update the "Assigned To" column and sort order
    const task = await prisma.task.update({
      where: { id: taskId },
      data: {
        columnId: targetColumnId,
        position,
      },
    })

    return Response.json({ success: true, task })
  } catch (error) {
    return Response.json({ error: 'Failed to move task' }, { status: 500 })
  }
}

Output:

TEXT 📖 Display only
Fade in/out: opacity 0→1 over 300ms. Toggle button shows/hides element with smooth CSS transition.

(3) Kanban Lists and Data Statistics

The board list page displays all boards created by users, with each board shown as a card that displays its name, creation date, and number of tasks. Statistics are presented using Recharts bar charts to show the distribution of tasks by priority, helping teams gain a clear understanding of their workload.

▶ Example 4: Kanban Lists and Statistical Charts

Output:

TEXT 📖 Display only
Async data fetching/loading states
TSX
// app/(dashboard)/page.tsx - Dashboard Home Page(List of Kanban Boards + Statistics)
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { redirect } from 'next/navigation'
import DashboardClient from './DashboardClient'

async function DashboardPage() {
  const session = await auth()
  if (!session?.user?.id) redirect('/login')

  // Get the user's list of boards
  const boards = await prisma.board.findMany({
    where: { ownerId: session.user.id },
    include: {
      _count: { select: { tasks: true } },
    },
    orderBy: { updatedAt: 'desc' },
  })

  // Get statistics on the number of tasks by priority
  const taskPriorityCounts = await prisma.task.groupBy({
    by: ['priority'],
    where: {
      board: { ownerId: session.user.id },
    },
    _count: true,
  })

  const stats = {
    totalTasks: taskPriorityCounts.reduce((sum, item) => sum + item._count, 0),
    priorityData: taskPriorityCounts.map(item => ({
      priority: item.priority,
      count: item._count,
    })),
  }

  return (
    <DashboardClient
      boards={JSON.parse(JSON.stringify(boards))}
      stats={JSON.parse(JSON.stringify(stats))}
    />
  )
}
export default DashboardPage

// app/(dashboard)/DashboardClient.tsx
'use client'
import { Card, Row, Col, Statistic, Typography } from 'antd'
import { PlusOutlined, ProjectOutlined, CheckCircleOutlined } from '@ant-design/icons'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import Link from 'next/link'

const { Title } = Typography

const priorityLabels: Record<string, string> = {
  urgent: 'Urgent',
  high: 'High',
  middle: 'in ',
  low: 'Low',
}

const priorityColors: Record<string, string> = {
  urgent: '#ff4d4f',
  high: '#fa8c16',
  middle: '#1677ff',
  low: '#52c41a',
}

function DashboardClient({ boards, stats }: { boards: any[], stats: any }) {
  const chartData = stats.priorityData.map((d: any) => ({
    name: priorityLabels[d.priority] || d.priority,
    count: d.count,
    fill: priorityColors[d.priority] || '#1677ff',
  }))

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={3} style={{ margin: 0 }}>My Board</Title>
        <Link href="/board/new">
          <Card
            hoverable
            style={{ width: 200, textAlign: 'center', borderStyle: 'dashed' }}
          >
            <PlusOutlined style={{ fontSize: 24, color: '#1677ff' }} />
            <div style={{ marginTop: 8 }}>Create a Kanban Board</div>
          </Card>
        </Link>
      </div>

      {/* Statistical Overview */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Number of Tasks"
              value={stats.totalTasks}
              prefix={<ProjectOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Number of boards"
              value={boards.length}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* Priority Distribution Chart */}
      <Card title="Distribution of Task Priorities" style={{ marginBottom: 24 }}>
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" />
            <YAxis allowDecimals={false} />
            <Tooltip />
            <Bar dataKey="count" name="Quantity" radius={[4, 4, 0, 0]}>
              {chartData.map((entry: any, index: number) => (
                <rect key={index} fill={entry.fill} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </Card>

      {/* List of Kanban Boards */}
      <Row gutter={[16, 16]}>
        {boards.map((board: any) => (
          <Col key={board.id} span={8}>
            <Link href={`/board/${board.id}`}>
              <Card
                hoverable
                style={{ borderTop: `3px solid ${board.color || '#1677ff'}` }}
              >
                <Card.Meta
                  title={board.title}
                  description={`${board._count.tasks} A task`}
                />
              </Card>
            </Link>
          </Col>
        ))}
      </Row>
    </div>
  )
}
export default DashboardClient

Output:

TEXT 📖 Display only
"use client" directive → component renders on client. Required for useState, useEffect, onClick. Without it → Server Component (default).

▶ Example 5: Sorting Tasks by Dragging and Dropping — Server Action

Output:

TEXT 📖 Display only
Displays: "My Board". Async data fetching/loading states
TSX
// app/actions/board-actions.ts - Server-Side Drag-and-Drop Sorting
'use server'
import { prisma } from '@/lib/prisma'
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'

export async function moveTask(taskId: string, targetColumnId: string, newPosition: number) {
  const session = await auth()
  if (!session?.user) throw new Error('Unauthorized')

  const task = await prisma.task.findUnique({
    where: { id: taskId },
    include: { board: true },
  })

  if (!task || task.board.userId !== session.user.id) {
    throw new Error('Task not found or no permission')
  }

  await prisma.$transaction(async (tx) => {
    await tx.task.updateMany({
      where: { columnId: targetColumnId, position: { gte: newPosition } },
      data: { position: { increment: 1 } },
    })

    await tx.task.update({
      where: { id: taskId },
      data: { columnId: targetColumnId, position: newPosition },
    })
  })

  revalidatePath(`/board/${task.boardId}`)
}

export async function createTask(columnId: string, title: string, priority: string) {
  const session = await auth()
  if (!session?.user) throw new Error('Unauthorized')

  const column = await prisma.column.findUnique({
    where: { id: columnId },
    include: { board: true },
  })

  if (!column || column.board.userId !== session.user.id) {
    throw new Error('Column not found or no permission')
  }

  const maxPosition = await prisma.task.findMany({
    where: { columnId },
    orderBy: { position: 'desc' },
    take: 1,
    select: { position: true },
  })

  const task = await prisma.task.create({
    data: {
      title,
      priority: priority as any,
      columnId,
      boardId: column.boardId,
      position: (maxPosition[0]?.position ?? -1) + 1,
    },
  })

  revalidatePath(`/board/${column.boardId}`)
  return task
}

Output:

TEXT 📖 Display only
ISR: revalidate: 30 → page served from cache, background regenerates after 30s. Always fast, data stays fresh.

❓ FAQ

Q How long will it take to complete this project?
A If you follow the steps in this lesson, a developer with full-stack experience (both front-end and back-end) will need about 3–5 days (20–30 hours). Beginners may need 1–2 weeks. We recommend completing the project in stages by functional module: start with database design and authentication (Day 1), then move on to the Kanban board and data visualization (Days 2–3), and finally tackle the drag-and-drop functionality and deployment (Days 4–5). Each module can be tested independently once completed.
Q How is multi-tenant data isolation implemented?
A The multi-tenant model in this project is based on "user-owned Kanban boards." Each Board record is associated with a ownerId, and all data queries include a ownerId filter (e.g., where: { ownerId: session.user.id }). No multi-tenant isolation is required at the database level (no "schema-per-tenant" is needed); conditional queries at the application layer are sufficient. If team collaboration is required (multiple users sharing a single Kanban board), an Team association model can be added to Board.
Q How do I choose between @dnd-kit and react-beautiful-dnd?
A react-beautiful-dnd used to be the most popular React drag-and-drop library, but Atlassian has announced that it will no longer maintain it, and it no longer supports Strict Mode in React 18+. @dnd-kit is currently the recommended choice—it’s lighter (about 15KB), has a more modern API design, and supports a wider range of drag-and-drop scenarios (sorting by dragging, drop-and-place, multi-container dragging, and draggable handles). The DndContext + SortableContext + useSortable pattern used in this project is the most common combination in @dnd-kit.
Q How do I deploy this project to a production environment?
A We recommend using the combination of Vercel and Supabase (PostgreSQL). Supabase provides a free PostgreSQL database (500MB), and Vercel offers one-click deployment for Next.js. Set the environment variables (DATABASE_URL, NEXTAUTH_SECRET, GOOGLE_CLIENT_ID, etc.) in the Vercel Dashboard. Before deploying, run npx prisma generate and npx prisma db push to initialize the database. You can reuse the CI/CD configuration from Section 28 of this course.
Q How can this project be scaled for multi-user collaboration?
A Three expansion directions: ① Real-time collaboration—introduce WebSockets (such as Socket.io or Supabase Realtime) to broadcast changes to other online users when a user drags a card; ② Permission management—add the members field to the Board model to distinguish between Owner, Editor, and Viewer roles; ③ Notification system—send email or browser notifications when cards are assigned or deadlines are approaching. Tech stack upgrade roadmap: Supabase Realtime + NextAuth.js RBAC + Web Push API.

📖 Summary


📝 Exercises

  1. Follow the steps in this lesson to set up the project skeleton: create a Next.js project, configure the Prisma database schema, and run npx prisma db push to initialize the data tables. Create a free PostgreSQL database in Supabase and configure the connection string in the .env file. Verify that prisma db push executes successfully.
  2. Implement the drag-and-drop functionality for @dnd-kit’s kanban board: Configure DndContext (PointerSensor + KeyboardSensor); implement the handleDragEnd function to handle cross-column moves and sorting within the same column; and use the PUT API to synchronize the drag-and-drop results to the database. After dragging, refresh the page to verify that the kanban board’s state has been correctly persisted.
  3. Deployment and Launch: Push the project to the GitHub repository and connect it to Vercel for automatic deployment. Add all environment variables (DATABASE_URL, NEXTAUTH_SECRET, GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET) in the Vercel Dashboard. Once deployment is complete, create a test board, add tasks, and test the drag-and-drop functionality to verify that all features are working properly in the production environment.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏