基于Next.js的医疗健康管理系统源码全解析与实战部署指南

引言:现代医疗健康管理系统的技术选型
在数字化医疗快速发展的今天,构建一个高效、安全、可扩展的医疗健康管理系统变得至关重要。Next.js作为React生态中最流行的全栈框架,凭借其服务端渲染(SSR)、静态生成(SSG)、API路由以及内置的TypeScript支持等特性,成为构建复杂Web应用的理想选择。
医疗健康管理系统通常包含以下核心需求:
数据敏感性
:处理患者的个人健康信息(PHI),需要严格遵守HIPAA等法规
实时性
:医生需要实时查看患者数据,患者需要及时接收通知
高可用性
:系统必须保证7×24小时稳定运行
用户体验
:医生和患者都需要直观、易用的界面
本文将通过一个完整的实战案例,详细解析如何使用Next.js构建医疗健康管理系统,涵盖从项目初始化到生产部署的全过程。
1. 项目架构设计
1.1 技术栈选择
{
“frontend”: {
“framework”: “Next.js 14 (App Router)”,
“ui_library”: “Shadcn UI + Tailwind CSS”,
“state_management”: “Zustand”,
“form_handling”: “React Hook Form + Zod”,
“data_fetching”: “React Query”
},
“backend”: {
“framework”: “Next.js API Routes”,
“database”: “PostgreSQL with Prisma ORM”,
“authentication”: “NextAuth.js”,
“authorization”: “Custom RBAC middleware”,
“file_storage”: “AWS S3 / Supabase Storage”
},
“infrastructure”: {
“hosting”: “Vercel / AWS”,
“database_host”: “Supabase / AWS RDS”,
“caching”: “Redis”,
“monitoring”: “Sentry + Vercel Analytics”
}
}
1.2 系统模块划分
src/
├── app/ # Next.js App Router
│ ├── (public)/ # 公共路由(登录、注册等)
│ ├── (dashboard)/ # 仪表盘布局
│ │ ├── doctor/ # 医生端功能
│ │ ├── patient/ # 患者端功能
│ │ └── admin/ # 管理员功能
│ └── api/ # API 路由
├── components/ # 可复用组件
│ ├── ui/ # 基础UI组件
│ ├── dashboard/ # 业务组件
│ └── medical/ # 医疗专用组件
├── lib/ # 工具函数和配置
│ ├── auth.ts # 认证配置
│ ├── db.ts # 数据库连接
│ ├── email.ts # 邮件服务
│ └── pdf.ts # PDF生成
├── stores/ # 状态管理
├── types/ # TypeScript类型定义
├── hooks/ # 自定义Hooks
├── utils/ # 辅助函数
└── styles/ # 全局样式
1.3 数据库设计
使用Prisma作为ORM,核心数据模型如下:
// prisma/schema.prisma

generator client {
provider = “prisma-client-js”
}

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

model User {
id String @id @default(cuid())
email String @unique
password String // 存储哈希后的密码
role Role @default(PATIENT)
profile Profile?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

// 关联关系
doctorPatients PatientDoctor[] @relation(“DoctorPatients”)
patientDoctors PatientDoctor[] @relation(“PatientDoctors”)
appointments Appointment[] @relation(“AppointmentDoctor”)
patientAppointments Appointment[] @relation(“AppointmentPatient”)
medicalRecords MedicalRecord[]
prescriptions Prescription[]
notifications Notification[]

@@index([email])
@@map(“users”)
}

enum Role {
ADMIN
DOCTOR
PATIENT
}

model Profile {
id String @id @default(cuid())
userId String @unique
firstName String
lastName String
phone String?
address String?
dob DateTime?
gender Gender?
avatarUrl String?

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@map(“profiles”)
}

model PatientDoctor {
id String @id @default(cuid())
patientId String
doctorId String
status InvitationStatus @default(PENDING)
createdAt DateTime @default(now())

patient User @relation(fields: [patientId], references: [id], onDelete: Cascade)
doctor User @relation(fields: [doctorId], references: [id], onDelete: Cascade)

@@unique([patientId, doctorId])
@@map(“patient_doctors”)
}

model Appointment {
id String @id @default(cuid())
patientId String
doctorId String
date DateTime
reason String
status AppointmentStatus @default(SCHEDULED)
notes String?
meetingLink String? // 视频会议链接
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

patient User @relation(fields: [patientId], references: [id], onDelete: Cascade)
doctor User @relation(fields: [doctorId], references: [id], onDelete: Cascade)

@@index([patientId, date])
@@index([doctorId, date])
@@map(“appointments”)
}

enum AppointmentStatus {
SCHEDULED
COMPLETED
CANCELLED
NO_SHOW
}

model MedicalRecord {
id String @id @default(cuid())
patientId String
doctorId String
title String
description String
files String[] // 存储文件URL
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

patient User @relation(fields: [patientId], references: [id], onDelete: Cascade)
doctor User @relation(fields: [doctorId], references: [id], onDelete: Cascade)

@@index([patientId, createdAt])
@@map(“medical_records”)
}

model Prescription {
id String @id @default(cuid())
patientId String
doctorId String
medication String
dosage String
frequency String
duration String
instructions String?
startDate DateTime
endDate DateTime
status PrescriptionStatus @default(ACTIVE)
createdAt DateTime @default(now())

patient User @relation(fields: [patientId], references: [id], onDelete: Cascade)
doctor User @relation(fields: [doctorId], references: [id], onDelete: Cascade)

@@index([patientId, startDate])
@@index([doctorId, startDate])
@@map(“prescriptions”)
}

enum PrescriptionStatus {
ACTIVE
COMPLETED
CANCELLED
}

model Notification {
id String @id @default(cuid())
userId String
title String
message String
type NotificationType
read Boolean @default(false)
createdAt DateTime @default(now())

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@index([userId, read, createdAt])
@@map(“notifications”)
}

enum NotificationType {
APPOINTMENT
PRESCRIPTION
GENERAL
ALERT
}

model AuditLog {
id String @id @default(cuid())
userId String?
action String
resource String
resourceId String?
ipAddress String?
userAgent String?
createdAt DateTime @default(now())

@@index([userId, createdAt])
@@index([resource, resourceId])
@@map(“audit_logs”)
}

enum Gender {
MALE
FEMALE
OTHER
PREFER_NOT_TO_SAY
}

enum InvitationStatus {
PENDING
ACCEPTED
REJECTED
}
2. 项目初始化与配置
2.1 创建Next.js项目
# 使用Create Next App创建项目
npx create-next-app@latest medical-dashboard –typescript –tailwind –eslint –app –src-dir –import-alias “@/*”

# 进入项目目录
cd medical-dashboard

# 安装核心依赖
npm install @prisma/client @auth/prisma-adapter next-auth prisma
npm install @hookform/resolvers zod react-hook-form
npm install @tanstack/react-query @tanstack/react-query-devtools
npm install zustand zustand middleware
npm install date-fns axios
npm install clsx tailwind-merge

# 安装UI库 (Shadcn UI)
npx shadcn-ui@latest init
npx shadcn-ui@latest add button card input label textarea select
2.2 环境变量配置
创建
.env.local
文件:
# 数据库
DATABASE_URL=”postgresql://user:password@localhost:5432/medical_db?schema=public”

# NextAuth
NEXTAUTH_URL=”http://localhost:3000″
NEXTAUTH_SECRET=”your-secret-key-change-in-production”

# 外部服务(开发环境可使用模拟服务)
AWS_ACCESS_KEY_ID=”dev-key”
AWS_SECRET_ACCESS_KEY=”dev-secret”
AWS_REGION=”us-east-1″
S3_BUCKET=”medical-records-dev”

# 邮件服务(开发环境使用Mailtrap或类似服务)
SMTP_HOST=”smtp.mailtrap.io”
SMTP_PORT=”2525″
SMTP_USER=”dev-user”
SMTP_PASS=”dev-pass”

# 生产环境URL
NEXT_PUBLIC_APP_URL=”http://localhost:3000″
2.3 Prisma配置与数据库迁移
// src/lib/db.ts
import { PrismaClient } from ‘@prisma/client’

const globalForPrisma = global as unknown as { prisma: PrismaClient }

export const prisma =
globalForPrisma.prisma ||
new PrismaClient({
log: [‘query’, ‘error’, ‘warn’],
})

if (process.env.NODE_ENV !== ‘production’) globalForPrisma.prisma = prisma
执行数据库迁移:
# 生成迁移文件
npx prisma migrate dev –name init

# 生成Prisma Client
npx prisma generate

# 可选:填充测试数据
npx prisma db seed
2.4 NextAuth.js 认证配置
// src/lib/auth.ts
import NextAuth from ‘next-auth’
import CredentialsProvider from ‘next-auth/providers/credentials’
import { prisma } from ‘./db’
import bcrypt from ‘bcryptjs’

export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
providers: [
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 },
include: { profile: true },
})

if (!user) {
return null
}

const isValid = await bcrypt.compare(
credentials.password as string,
user.password
)

if (!isValid) {
return null
}

return {
id: user.id,
email: user.email,
role: user.role,
name: user.profile?.firstName + ‘ ‘ + user.profile?.lastName,
image: user.profile?.avatarUrl,
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role
token.sub = user.id
}
return token
},
async session({ session, token }) {
if (session.user) {
session.user.role = token.role
session.user.id = token.sub as string
}
return session
},
},
pages: {
signIn: ‘/auth/login’,
signOut: ‘/auth/logout’,
},
})
2.5 中间件与路由保护
// src/middleware.ts
import { withAuth } from ‘next-auth/middleware’
import { NextResponse } from ‘next/server’

export default withAuth(
function middleware(req) {
const token = req.nextauth.token
const path = req.nextUrl.pathname

// 角色-based路由保护
if (path.startsWith(‘/dashboard/doctor’) && token?.role !== ‘DOCTOR’) {
return NextResponse.redirect(new URL(‘/dashboard/patient’, req.url))
}

if (path.startsWith(‘/dashboard/patient’) && token?.role !== ‘PATIENT’) {
return NextResponse.redirect(new URL(‘/dashboard/doctor’, req.url))
}

if (path.startsWith(‘/dashboard/admin’) && token?.role !== ‘ADMIN’) {
return NextResponse.redirect(new URL(‘/dashboard’, req.url))
}

return NextResponse.next()
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
}
)

export const config = {
matcher: [‘/dashboard/:path*’, ‘/api/protected/:path*’]
}
3. 核心功能实现
3.1 患者管理模块
3.1.1 患者列表页面(医生端)
// src/app/(dashboard)/doctor/patients/page.tsx
import { auth } from ‘@/lib/auth’
import { prisma } from ‘@/lib/db’
import { redirect } from ‘next/navigation’
import { PatientList } from ‘@/components/dashboard/doctor/PatientList’

export default async function DoctorPatientsPage() {
const session = await auth()

if (!session?.user?.role === ‘DOCTOR’) {
redirect(‘/dashboard’)
}

// 获取医生的所有患者
const patients = await prisma.patientDoctor.findMany({
where: {
doctorId: session.user.id,
status: ‘ACCEPTED’,
},
include: {
patient: {
include: {
profile: true,
},
},
},
orderBy: {
createdAt: ‘desc’,
},
})

return (

我的患者

管理和查看您的患者信息

)
}
// src/components/dashboard/doctor/PatientList.tsx
‘use client’

import { useState } from ‘react’
import { useRouter } from ‘next/navigation’
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from ‘@/components/ui/card’
import { Button } from ‘@/components/ui/button’
import { Badge } from ‘@/components/ui/badge’
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from ‘@/components/ui/dialog’
import { Input } from ‘@/components/ui/input’
import { Search, UserPlus, Calendar, FileText } from ‘lucide-react’
import { toast } from ‘@/hooks/use-toast’
import axios from ‘axios’

interface Patient {
id: string
patient: {
id: string
email: string
profile: {
firstName: string
lastName: string
phone?: string
dob?: Date
} | null
}
}

interface PatientListProps {
patients: Patient[]
}

export function PatientList({ patients }: PatientListProps) {
const router = useRouter()
const [searchTerm, setSearchTerm] = useState(”)
const [isInviteOpen, setIsInviteOpen] = useState(false)
const [inviteEmail, setInviteEmail] = useState(”)

const filteredPatients = patients.filter(({ patient }) => {
const fullName = `${patient.profile?.firstName} ${patient.profile?.lastName}`.toLowerCase()
return fullName.includes(searchTerm.toLowerCase()) ||
patient.email.toLowerCase().includes(searchTerm.toLowerCase())
})

const handleInvite = async () => {
try {
await axios.post(‘/api/doctor/invite-patient’, {
email: inviteEmail,
})
toast({
title: ‘邀请已发送’,
description: ‘患者将收到连接请求’,
})
setIsInviteOpen(false)
setInviteEmail(”)
router.refresh()
} catch (error) {
toast({
title: ‘发送失败’,
description: ‘请检查邮箱地址或稍后重试’,
variant: ‘destructive’,
})
}
}

const viewMedicalRecord = (patientId: string) => {
router.push(`/dashboard/doctor/patients/${patientId}/records`)
}

const scheduleAppointment = (patientId: string) => {
router.push(`/dashboard/doctor/appointments/new?patient=${patientId}`)
}

return (

setSearchTerm(e.target.value)}
className=”max-w-sm”
icon={}
/>







邀请患者

输入患者的邮箱地址发送连接请求

setInviteEmail(e.target.value)}
/>


{filteredPatients.map(({ patient }) => (



{patient.profile?.firstName} {patient.profile?.lastName}
活跃

{patient.email}


{patient.profile?.phone && (

📱 {patient.profile.phone}

)}
{patient.profile?.dob && (

🎂 {new Date(patient.profile.dob).toLocaleDateString()}

)}




))}

{filteredPatients.length === 0 && (

暂无患者,请点击右上角邀请新患者

)}

)
}
3.1.2 API 路由:邀请患者
// src/app/api/doctor/invite-patient/route.ts
import { NextRequest, NextResponse } from ‘next/server’
import { auth } from ‘@/lib/auth’
import { prisma } from ‘@/lib/db’
import { sendEmail } from ‘@/lib/email’
import { z } from ‘zod’

const inviteSchema = z.object({
email: z.string().email(‘请输入有效的邮箱地址’),
})

export async function POST(request: NextRequest) {
const session = await auth()

if (!session?.user?.role === ‘DOCTOR’) {
return NextResponse.json(
{ error: ‘未授权’ },
{ status: 401 }
)
}

try {
const body = await request.json()
const { email } = inviteSchema.parse(body)

// 检查患者是否已存在
const existingPatient = await prisma.user.findUnique({
where: { email },
})

if (!existingPatient) {
return NextResponse.json(
{ error: ‘该患者尚未注册’ },
{ status: 400 }
)
}

if (existingPatient.role !== ‘PATIENT’) {
return NextResponse.json(
{ error: ‘该用户不是患者角色’ },
{ status: 400 }
)
}

// 检查是否已存在连接
const existingConnection = await prisma.patientDoctor.findUnique({
where: {
patientId_doctorId: {
patientId: existingPatient.id,
doctorId: session.user.id,
},
},
})

if (existingConnection) {
if (existingConnection.status === ‘ACCEPTED’) {
return NextResponse.json(
{ error: ‘该患者已是您的患者’ },
{ status: 400 }
)
}
return NextResponse.json(
{ error: ‘已发送邀请,请等待患者确认’ },
{ status: 400 }
)
}

// 创建邀请记录
await prisma.patientDoctor.create({
data: {
patientId: existingPatient.id,
doctorId: session.user.id,
status: ‘PENDING’,
},
})

// 发送邮件通知
const doctorProfile = await prisma.profile.findUnique({
where: { userId: session.user.id },
})

await sendEmail({
to: email,
subject: ‘医生连接请求’,
html: `

您收到一条医生连接请求

医生 ${doctorProfile?.firstName} ${doctorProfile?.lastName} 希望将您添加为患者。

请登录系统查看并接受请求。


查看请求

`,
})

// 创建通知
await prisma.notification.create({
data: {
userId: existingPatient.id,
type: ‘GENERAL’,
title: ‘医生连接请求’,
message: `医生 ${doctorProfile?.firstName} ${doctorProfile?.lastName} 请求连接`,
},
})

return NextResponse.json(
{ message: ‘邀请已发送’ },
{ status: 200 }
)
} catch (error) {
console.error(‘Invite error:’, error)
return NextResponse.json(
{ error: ‘服务器错误’ },
{ status: 500 }
)
}
}
3.2 预约管理模块
3.2.1 创建预约(医生端)
// src/components/dashboard/doctor/AppointmentForm.tsx
‘use client’

import { zodResolver } from ‘@hookform/resolvers/zod’
import { useForm } from ‘react-hook-form’
import { z } from ‘zod’
import { Button } from ‘@/components/ui/button’
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from ‘@/components/ui/form’
import { Input } from ‘@/components/ui/input’
import { Textarea } from ‘@/components/ui/textarea’
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from ‘@/components/ui/select’
import { DateTimePicker } from ‘@/components/ui/date-time-picker’
import { toast } from ‘@/hooks/use-toast’
import { useRouter } from ‘next/navigation’
import axios from ‘axios’

const appointmentSchema = z.object({
patientId: z.string().min(1, ‘请选择患者’),
date: z.date({
required_error: ‘请选择预约时间’,
}),
reason: z.string().min(1, ‘请输入预约原因’),
notes: z.string().optional(),
})

interface AppointmentFormProps {
patients: {
id: string
profile: {
firstName: string
lastName: string
} | null
}[]
}

export function AppointmentForm({ patients }: AppointmentFormProps) {
const router = useRouter()
const form = useForm>({
resolver: zodResolver(appointmentSchema),
defaultValues: {
patientId: ”,
reason: ”,
notes: ”,
},
})

async function onSubmit(values: z.infer) {
try {
const response = await axios.post(‘/api/doctor/appointments’, {
…values,
date: values.date.toISOString(),
})

if (response.status === 201) {
toast({
title: ‘预约创建成功’,
description: ‘患者将收到预约通知’,
})
router.push(‘/dashboard/doctor/appointments’)
router.refresh()
}
} catch (error) {
toast({
title: ‘创建失败’,
description: ‘请检查输入或稍后重试’,
variant: ‘destructive’,
})
}
}

return (

(

选择患者



)}
/>

(

预约时间





)}
/>

(

预约原因





)}
/>

(

备注(可选)