引言:为什么选择Next.js构建招聘平台?
在当今数字化时代,招聘求职平台已成为连接人才与企业的重要桥梁。传统的单页应用(SPA)虽然在交互体验上表现出色,但在SEO(搜索引擎优化)和首屏加载速度方面往往存在不足。而Next.js作为React生态中最流行的全栈框架,完美解决了这些问题。
Next.js的核心优势:
服务端渲染(SSR)与静态站点生成(SSG)
:极大提升首屏加载速度和SEO表现
API路由
:无需单独搭建后端服务,直接在项目中编写API接口
内置路由系统
:基于文件系统的路由,简化开发流程
TypeScript支持
:开箱即用的类型安全开发体验
图片优化
:自动优化图片资源,提升用户体验
对于招聘平台这类需要良好SEO(让企业职位被搜索引擎收录)和快速加载的应用,Next.js是不二之选。
一、项目初始化与技术选型
1.1 创建Next.js项目
首先,我们需要创建一个全新的Next.js项目。推荐使用TypeScript模板以获得更好的开发体验。
# 使用npm创建项目
npx create-next-app@latest job-platform –typescript –tailwind –eslint –app –src-dir –import-alias “@/*”
# 进入项目目录
cd job-platform
# 安装依赖(如果需要额外的包)
npm install
参数说明:
–typescript
:启用TypeScript支持
–tailwind
:使用Tailwind CSS进行样式开发
–app
:使用App Router(Next.js 13+的新特性)
–src-dir
:将源代码放在src目录下,保持项目结构清晰
1.2 项目目录结构规划
一个清晰的项目结构是成功开发的基础。以下是推荐的目录结构:
job-platform/
├── src/
│ ├── app/ # App Router路由和页面
│ │ ├── (auth)/ # 认证相关路由组
│ │ ├── (dashboard)/ # 仪表盘路由组
│ │ ├── api/ # API路由
│ │ ├── layout.tsx # 根布局
│ │ └── page.tsx # 首页
│ ├── components/ # 可复用组件
│ │ ├── ui/ # 基础UI组件(Button, Input等)
│ │ ├── job/ # 职位相关组件
│ │ └── user/ # 用户相关组件
│ ├── lib/ # 工具函数和配置
│ │ ├── db.ts # 数据库连接
│ │ ├── auth.ts # 认证配置
│ │ └── utils.ts # 通用工具函数
│ ├── types/ # TypeScript类型定义
│ ├── hooks/ # 自定义Hook
│ └── styles/ # 全局样式
├── public/ # 静态资源
├── prisma/ # Prisma schema(如果使用Prisma)
├── .env.local # 环境变量
├── next.config.js # Next.js配置
└── package.json # 项目依赖
1.3 技术栈选择
基于Next.js的招聘平台,推荐以下技术栈:
前端/全栈框架:
Next.js 14+
:基于React 18,支持App Router
React 18
:用于构建用户界面
样式:
Tailwind CSS
:原子化CSS框架,快速构建响应式界面
shadcn/ui
:基于Tailwind的可访问组件库(可选,但强烈推荐)
数据库与ORM:
PostgreSQL
:推荐使用Supabase或Vercel Postgres
Prisma
:现代化的数据库ORM,支持TypeScript类型安全
认证:
NextAuth.js
:最流行的Next.js认证库,支持多种登录方式(邮箱、OAuth等)
状态管理:
Zustand
:轻量级状态管理库,适合中小型项目
React Query
:服务端状态管理,处理数据获取、缓存和更新
表单验证:
React Hook Form
+
Zod
:表单处理与模式验证
其他工具:
ESLint & Prettier
:代码规范和格式化
Husky & lint-staged
:Git hooks,确保提交代码质量
二、数据库设计与实现
2.1 数据库模型设计
招聘平台的核心是数据模型。我们需要设计用户、公司、职位、申请等核心实体。
使用Prisma Schema定义模型:
// 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
name String?
password String? // 如果使用邮箱密码登录
image String?
role Role @default(CANDIDATE) // 角色:CANDIDATE/RECRUITER/ADMIN
emailVerified DateTime?
// 求职者特有字段
resume String? // 简历URL
skills String[] // 技能标签
experience Int? // 工作经验(年)
expectedSalary Int? // 期望薪资
// 招聘者特有字段
company Company? // 关联的公司
// 关联关系
applications Application[]
jobs Job[] // 发布的职位
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([email])
@@index([role])
}
// 公司模型
model Company {
id String @id @default(cuid())
name String
description String?
logo String?
website String?
industry String?
size String? // 公司规模:SMALL/MEDIUM/LARGE
// 关联关系
jobs Job[]
recruiterId String @unique
recruiter User @relation(fields: [recruiterId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
// 职位模型
model Job {
id String @id @default(cuid())
title String
description String
requirements String[] // 技能要求
location String // 工作地点
salaryMin Int // 最低薪资
salaryMax Int // 最高薪资
currency String @default(“CNY”) // 货币
type JobType // 全职/兼职/实习
remote Boolean @default(false) // 是否远程
// 关联关系
companyId String
company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
recruiterId String
recruiter User @relation(fields: [recruiterId], references: [id])
applications Application[]
status JobStatus @default(ACTIVE) // 职位状态
views Int @default(0) // 浏览次数
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([status])
@@index([location])
@@index([type])
@@index([salaryMin, salaryMax])
}
// 申请模型
model Application {
id String @id @default(cuid())
// 关联关系
jobId String
job Job @relation(fields: [jobId], references: [id], onDelete: Cascade)
candidateId String
candidate User @relation(fields: [candidateId], references: [id], onDelete: Cascade)
status ApplicationStatus @default(PENDING) // 申请状态
coverLetter String? // 求职信
resumeUrl String? // 自定义简历
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([jobId])
@@index([candidateId])
@@index([status])
}
// 枚举类型定义
enum Role {
CANDIDATE
RECRUITER
ADMIN
}
enum JobType {
FULL_TIME
PART_TIME
CONTRACT
INTERNSHIP
}
enum JobStatus {
ACTIVE
INACTIVE
CLOSED
}
enum ApplicationStatus {
PENDING
REVIEWED
ACCEPTED
REJECTED
}
2.2 数据库连接与初始化
在
src/lib/db.ts
中配置数据库连接:
// src/lib/db.ts
import { PrismaClient } from ‘@prisma/client’
// 防止开发模式下重复创建Prisma Client实例
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === ‘development’ ? [‘query’, ‘error’, ‘warn’] : [‘error’],
})
if (process.env.NODE_ENV !== ‘production’) globalForPrisma.prisma = prisma
环境变量配置:
在
.env.local
文件中添加数据库连接字符串:
DATABASE_URL=”postgresql://user:password@localhost:5432/jobplatform?schema=public”
运行迁移:
# 生成迁移文件
npx prisma migrate dev –name init
# 生成Prisma Client
npx prisma generate
三、认证系统实现
3.1 NextAuth.js配置
NextAuth.js是Next.js生态中最成熟的认证解决方案。我们将实现邮箱密码登录和OAuth登录(如GitHub)。
# 安装NextAuth.js
npm install next-auth
配置NextAuth.js:
// src/app/api/auth/[…nextauth]/route.ts
import NextAuth from “next-auth”
import CredentialsProvider from “next-auth/providers/credentials”
import GithubProvider from “next-auth/providers/github”
import { prisma } from “@/lib/db”
import bcrypt from “bcryptjs”
const handler = NextAuth({
providers: [
// GitHub OAuth登录
GithubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
// 邮箱密码登录
CredentialsProvider({
name: “credentials”,
credentials: {
email: { label: “Email”, type: “email” },
password: { label: “Password”, type: “password” }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
throw new Error(“Email and password are required”)
}
const user = await prisma.user.findUnique({
where: { email: credentials.email as string }
})
if (!user || !user.password) {
throw new Error(“No user found with this email”)
}
const isValid = await bcrypt.compare(
credentials.password as string,
user.password
)
if (!isValid) {
throw new Error(“Invalid password”)
}
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
}
}
})
],
callbacks: {
// JWT回调:在token中添加自定义字段
async jwt({ token, user }) {
if (user) {
token.role = user.role
token.id = user.id
}
return token
},
// Session回调:在session中暴露自定义字段
async session({ session, token }) {
if (session.user) {
session.user.role = token.role
session.user.id = token.id
}
return session
},
// OAuth登录时,自动创建用户记录
async signIn({ user, account, profile }) {
if (account?.provider === “github” && profile?.email) {
const existingUser = await prisma.user.findUnique({
where: { email: profile.email as string }
})
if (!existingUser) {
await prisma.user.create({
data: {
email: profile.email as string,
name: profile.name || profile.login,
image: profile.avatar_url,
role: “CANDIDATE”, // 默认为求职者
}
})
}
}
return true
}
},
pages: {
signIn: “/auth/signin”, // 自定义登录页面
},
secret: process.env.NEXTAUTH_SECRET,
})
export { handler as GET, handler as POST }
3.2 注册API实现
// src/app/api/auth/register/route.ts
import { NextRequest, NextResponse } from “next/server”
import { prisma } from “@/lib/db”
import bcrypt from “bcryptjs”
import { z } from “zod”
// 验证schema
const registerSchema = z.object({
email: z.string().email(“Invalid email format”),
password: z.string().min(8, “Password must be at least 8 characters”),
name: z.string().min(2, “Name must be at least 2 characters”),
role: z.enum([“CANDIDATE”, “RECRUITER”]),
})
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { email, password, name, role } = registerSchema.parse(body)
// 检查用户是否已存在
const existingUser = await prisma.user.findUnique({
where: { email }
})
if (existingUser) {
return NextResponse.json(
{ error: “User already exists” },
{ status: 400 }
)
}
// 哈希密码
const hashedPassword = await bcrypt.hash(password, 12)
// 创建用户
const user = await prisma.user.create({
data: {
email,
password: hashedPassword,
name,
role,
},
select: {
id: true,
email: true,
name: true,
role: true,
}
})
return NextResponse.json(
{ message: “User created successfully”, user },
{ status: 201 }
)
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: error.errors },
{ status: 400 }
)
}
return NextResponse.json(
{ error: “Internal server error” },
{ status: 500 }
)
}
}
3.3 保护路由与页面
使用Next.js的Middleware保护需要认证的路由:
// 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
// 管理员只能访问/admin开头的路由
if (path.startsWith(“/admin”) && token?.role !== “ADMIN”) {
return NextResponse.redirect(new URL(“/dashboard”, req.url))
}
// 招聘者只能访问/recruiter开头的路由
if (path.startsWith(“/recruiter”) && token?.role !== “RECRUITER”) {
return NextResponse.redirect(new URL(“/dashboard”, req.url))
}
return NextResponse.next()
},
{
callbacks: {
// 只有认证用户才能访问受保护的路由
authorized: ({ token }) => !!token,
},
}
)
export const config = {
matcher: [
“/dashboard/:path*”,
“/recruiter/:path*”,
“/admin/:path*”,
“/profile/:path*”,
],
}
3.4 自定义登录页面
// src/app/auth/signin/page.tsx
“use client”
import { signIn, getCsrfToken } from “next-auth/react”
import { useSearchParams } from “next/navigation”
import { useState } from “react”
import { z } from “zod”
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
})
export default function SignInPage() {
const searchParams = useSearchParams()
const callbackUrl = searchParams.get(“callbackUrl”) || “/dashboard”
const [error, setError] = useState
const [loading, setLoading] = useState(false)
async function handleSubmit(e: React.FormEvent
e.preventDefault()
setLoading(true)
setError(null)
const formData = new FormData(e.currentTarget)
const email = formData.get(“email”) as string
const password = formData.get(“password”) as string
// 验证输入
try {
loginSchema.parse({ email, password })
} catch (error) {
setError(“Invalid email or password format”)
setLoading(false)
return
}
const result = await signIn(“credentials”, {
email,
password,
redirect: false,
callbackUrl,
})
if (result?.error) {
setError(result.error)
} else if (result?.url) {
window.location.href = result.url
}
setLoading(false)
}
return (
)
}
四、核心功能开发
4.1 职位发布功能(招聘者)
API路由:
// src/app/api/jobs/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { prisma } from “@/lib/db”
import { z } from “zod”
const jobSchema = z.object({
title: z.string().min(3, “Title must be at least 3 characters”),
description: z.string().min(50, “Description must be at least 50 characters”),
requirements: z.array(z.string()).min(1, “At least one requirement is required”),
location: z.string().min(2, “Location is required”),
salaryMin: z.number().min(0),
salaryMax: z.number().min(0),
type: z.enum([“FULL_TIME”, “PART_TIME”, “CONTRACT”, “INTERNSHIP”]),
remote: z.boolean().default(false),
companyId: z.string().cuid(),
})
// GET /api/jobs – 获取职位列表
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const page = parseInt(searchParams.get(“page”) || “1”)
const limit = parseInt(searchParams.get(“limit”) || “10”)
const location = searchParams.get(“location”)
const type = searchParams.get(“type”)
const search = searchParams.get(“search”)
const where: any = {
status: “ACTIVE”,
}
if (location) where.location = { contains: location, mode: ‘insensitive’ }
if (type) where.type = type
if (search) {
where.OR = [
{ title: { contains: search, mode: ‘insensitive’ } },
{ description: { contains: search, mode: ‘insensitive’ } },
]
}
const [jobs, total] = await Promise.all([
prisma.job.findMany({
where,
include: {
company: {
select: {
id: true,
name: true,
logo: true,
},
},
recruiter: {
select: {
id: true,
name: true,
},
},
},
orderBy: { createdAt: “desc” },
skip: (page – 1) * limit,
take: limit,
}),
prisma.job.count({ where }),
])
return NextResponse.json({
jobs,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit),
},
})
} catch (error) {
return NextResponse.json(
{ error: “Failed to fetch jobs” },
{ status: 500 }
)
}
}
// POST /api/jobs – 发布新职位
export async function POST(request: NextRequest) {
const session = await getServerSession()
if (!session?.user?.email) {
return NextResponse.json({ error: “Unauthorized” }, { status: 401 })
}
// 验证用户是否为招聘者
const user = await prisma.user.findUnique({
where: { email: session.user.email },
select: { role: true, id: true },
})
if (user?.role !== “RECRUITER”) {
return NextResponse.json(
{ error: “Only recruiters can post jobs” },
{ status: 403 }
)
}
try {
const body = await request.json()
const data = jobSchema.parse(body)
// 验证公司归属权
const company = await prisma.company.findFirst({
where: {
id: data.companyId,
recruiterId: user.id,
},
})
if (!company) {
return NextResponse.json(
{ error: “You don’t have permission to post for this company” },
{ status: 403 }
)
}
const job = await prisma.job.create({
data: {
…data,
recruiterId: user.id,
},
include: {
company: true,
},
})
return NextResponse.json(job, { status: 201 })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: error.errors },
{ status: 400 }
)
}
return NextResponse.json(
{ error: “Failed to create job” },
{ status: 500 }
)
}
}
前端发布表单:
// src/app/recruiter/post-job/page.tsx
“use client”
import { useState } from “react”
import { useRouter } from “next/navigation”
import { useSession } from “next-auth/react”
import { z } from “zod”
const jobSchema = z.object({
title: z.string().min(3),
description: z.string().min(50),
requirements: z.string().transform(val => val.split(‘,’).map(r => r.trim()).filter(r => r)),
location: z.string().min(2),
salaryMin: z.number().min(0),
salaryMax: z.number().min(0),
type: z.enum([“FULL_TIME”, “PART_TIME”, “CONTRACT”, “INTERNSHIP”]),
remote: z.boolean(),
companyId: z.string().cuid(),
})
export default function PostJobPage() {
const { data: session } = useSession()
const router = useRouter()
const [loading, setLoading] = useState(false)
const [error, setError] = useState
async function handleSubmit(e: React.FormEvent
e.preventDefault()
setLoading(true)
setError(null)
const formData = new FormData(e.currentTarget)
const data = {
title: formData.get(“title”),
description: formData.get(“description”),
requirements: formData.get(“requirements”),
location: formData.get(“location”),
salaryMin: Number(formData.get(“salaryMin”)),
salaryMax: Number(formData.get(“salaryMax”)),
type: formData.get(“type”),
remote: formData.get(“remote”) === “on”,
companyId: formData.get(“companyId”),
}
try {
const validated = jobSchema.parse(data)
const response = await fetch(“/api/jobs”, {
method: “POST”,
headers: { “Content-Type”: “application/json” },
body: JSON.stringify(validated),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || “Failed to post job”)
}
router.push(“/recruiter/dashboard”)
} catch (error) {
if (error instanceof z.ZodError) {
setError(error.errors[0].message)
} else if (error instanceof Error) {
setError(error.message)
} else {
setError(“An unexpected error occurred”)
}
} finally {
setLoading(false)
}
}
return (
Post a New Job
{error && (
)}
)
}
4.2 职位搜索与筛选功能
API路由:
// src/app/api/jobs/search/route.ts
import { NextRequest, NextResponse } from “next/server”
import { prisma } from “@/lib/db”
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
// 获取查询参数
const query = searchParams.get(“q”) || “”
const location = searchParams.get(“location”)
const type = searchParams.get(“type”)
const remote = searchParams.get(“remote”)
const minSalary = searchParams.get(“minSalary”)
const maxSalary = searchParams.get(“maxSalary”)
const page = parseInt(searchParams.get(“page”) || “1”)
const limit = parseInt(searchParams.get(“limit”) || “10”)
// 构建查询条件
const where: any = {
status: “ACTIVE”,
AND: [],
}
// 全文搜索
if (query) {
where.AND.push({
OR: [
{ title: { contains: query, mode: ‘insensitive’ } },
{ description: { contains: query, mode: ‘insensitive’ } },
{ requirements: { has: query } },
],
})
}
// 地点筛选
if (location) {
where.AND.push({
location: { contains: location, mode: ‘insensitive’ }
})
}
// 职位类型筛选
if (type) {
where.AND.push({ type })
}
// 远程工作筛选
if (remote === “true”) {
where.AND.push({ remote: true })
}
// 薪资范围筛选
if (minSalary || maxSalary) {
where.AND.push({
AND: [
minSalary ? { salaryMin: { gte: parseInt(minSalary) } } : {},
maxSalary ? { salaryMax: { lte: parseInt(maxSalary) } } : {},
],
})
}
// 执行查询
const [jobs, total] = await Promise.all([
prisma.job.findMany({
where,
include: {
company: {
select: {
id: true,
name: true,
logo: true,
industry: true,
},
},
recruiter: {
select: {
id: true,
name: true,
},
},
},
orderBy: { createdAt: “desc” },
skip: (page – 1) * limit,
take: limit,
}),
prisma.job.count({ where }),
])
// 计算分页信息
const pagination = {
page,
limit,
total,
pages: Math.ceil(total / limit),
hasNext: page < Math.ceil(total / limit),
hasPrev: page > 1,
}
return NextResponse.json({
success: true,
data: jobs,
pagination,
})
} catch (error) {
console.error(“Search error:”, error)
return NextResponse.json(
{ success: false, error: “Search failed” },
{ status: 500 }
)
}
}
前端搜索组件:
// src/components/job/JobSearch.tsx
“use client”
import { useState, useEffect, useCallback } from “react”
import { useRouter, useSearchParams } from “next/navigation”
import { useDebounce } from “@/hooks/useDebounce”
export default function JobSearch() {
const router = useRouter()
const searchParams = useSearchParams()
// 从URL获取初始值
const [query, setQuery] = useState(searchParams.get(“q”) || “”)
const [location, setLocation] = useState(searchParams.get(“location”) || “”)
const [type, setType] = useState(searchParams.get(“type”) || “”)
const [remote, setRemote] = useState(searchParams.get(“remote”) === “true”)
// 防抖搜索
const debouncedQuery = useDebounce(query, 500)
const debouncedLocation = useDebounce(location, 500)
// 构建查询字符串
const buildQueryString = useCallback(() => {
const params = new URLSearchParams()
if (debouncedQuery) params.set(“q”, debouncedQuery)
if (debouncedLocation) params.set(“location”, debouncedLocation)
if (type) params.set(“type”, type)
if (remote) params.set(“remote”, “true”)
return params.toString()
}, [debouncedQuery, debouncedLocation, type, remote])
// 当搜索条件变化时更新URL
useEffect(() => {
const queryString = buildQueryString()
router.push(`/jobs?${queryString}`, { scroll: false })
}, [buildQueryString, router])
const handleRemoteChange = (e: React.ChangeEvent
setRemote(e.target.checked)
}
const clearFilters = () => {
setQuery(“”)
setLocation(“”)
setType(“”)
setRemote(false)
router.push(“/jobs”)
}
return (
setQuery(e.target.value)}
placeholder=”e.g., Frontend Developer”
className=”w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent”
/>
{/* 地点 */}
setLocation(e.target.value)}
placeholder=”e.g., Beijing”
className=”w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent”
/>
{/* 职位类型 */}
{/* 高级筛选 */}
{(query || location || type || remote) && (
)}
)
}
// src/hooks/useDebounce.ts
import { useState, useEffect } from “react”
export function useDebounce
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
}, [value, delay])
return debouncedValue
}
4.3 职位申请功能
API路由:
// src/app/api/jobs/[id]/apply/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { prisma } from “@/lib/db”
import { z } from “zod”
const applicationSchema = z.object({
coverLetter: z.string().optional(),
resumeUrl: z.string().url().optional(),
})
// POST /api/jobs/[id]/apply – 申请职位
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const session = await getServerSession()
if (!session?.user?.email) {
return NextResponse.json({ error: “Unauthorized” }, { status: 401 })
}
// 验证用户是否为求职者
const user = await prisma.user.findUnique({
where: { email: session.user.email },
select: { role: true, id: true },
})
if (user?.role !== “CANDIDATE”) {
return NextResponse.json(
{ error: “Only candidates can apply for jobs” },
{ status: 403 }
)
}
try {
// 检查职位是否存在且活跃
const job = await prisma.job.findUnique({
where: {
id: params.id,
status: “ACTIVE”,
},
})
if (!job) {
return NextResponse.json(
{ error: “Job not found or no longer active” },
{ status: 404 }
)
}
// 检查是否已申请
const existingApplication = await prisma.application.findUnique({
where: {
jobId_candidateId: {
jobId: params.id,
candidateId: user.id,
},
},
})
if (existingApplication) {
return NextResponse.json(
{ error: “You have already applied for this job” },
{ status: 400 }
)
}
const body = await request.json()
const { coverLetter, resumeUrl } = applicationSchema.parse(body)
// 创建申请记录
const application = await prisma.application.create({
data: {
jobId: params.id,
candidateId: user.id,
coverLetter,
resumeUrl,
},
include: {
job: {
include: {
company: true,
},
},
candidate: {
select: {
id: true,
name: true,
email: true,
resume: true,
skills: true,
experience: true,
},
},
},
})
return NextResponse.json(
{
success: true,
message: “Application submitted successfully”,
data: application,
},
{ status: 201 }
)
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: error.errors },
{ status: 400 }
)
}
return NextResponse.json(
{ error: “Failed to submit application” },
{ status: 500 }
)
}
}
// GET /api/jobs/[id]/apply – 检查是否已申请
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const session = await getServerSession()
if (!session?.user?.email) {
return NextResponse.json({ error: “Unauthorized” }, { status: 401 })
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
select: { id: true },
})
if (!user) {
return NextResponse.json({ error: “User not found” }, { status: 404 })
}
const application = await prisma.application.findUnique({
where: {
jobId_candidateId: {
jobId: params.id,
candidateId: user.id,
},
},
})
return NextResponse.json({
hasApplied: !!application,
application,
})
}
前端申请组件:
// src/components/job/ApplyButton.tsx
“use client”
import { useState, useEffect } from “react”
import { useSession } from “next-auth/react”
import { useRouter } from “next/navigation”
interface ApplyButtonProps {
jobId: string
}
export default function ApplyButton({ jobId }: ApplyButtonProps) {
const { data: session, status } = useSession()
const router = useRouter()
const [hasApplied, setHasApplied] = useState(false)
const [loading, setLoading] = useState(false)
const [showModal, setShowModal] = useState(false)
const [coverLetter, setCoverLetter] = useState(“”)
const [resumeUrl, setResumeUrl] = useState(“”)
// 检查是否已申请
useEffect(() => {
if (status === “authenticated”) {
fetch(`/api/jobs/${jobId}/apply`)
.then(res => res.json())
.then(data => {
if (data.hasApplied) {
setHasApplied(true)
}
})
}
}, [jobId, status])
const handleApply = async () => {
if (!session) {
router.push(`/auth/signin?callbackUrl=/jobs/${jobId}`)
return
}
if (session.user?.role !== “CANDIDATE”) {
alert(“Only candidates can apply for jobs”)
return
}
setShowModal(true)
}
const submitApplication = async () => {
setLoading(true)
try {
const response = await fetch(`/api/jobs/${jobId}/apply`, {
method: “POST”,
headers: { “Content-Type”: “application/json” },
body: JSON.stringify({ coverLetter, resumeUrl }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || “Failed to apply”)
}
setHasApplied(true)
setShowModal(false)
alert(“Application submitted successfully!”)
} catch (error) {
alert(error instanceof Error ? error.message : “Failed to apply”)
} finally {
setLoading(false)
}
}
if (status === “loading”) {
return
}
if (hasApplied) {
return (
)
}
return (
<>
{showModal && (
Submit Application
setResumeUrl(e.target.value)}
className=”w-full p-2 border rounded”
placeholder=”https://example.com/resume.pdf”
/>
)}
>
)
}
4.4 仪表盘功能
招聘者仪表盘:
// src/app/recruiter/dashboard/page.tsx
import { getServerSession } from “next-auth”
import { redirect } from “next/navigation”
import { prisma } from “@/lib/db”
import { Card, CardContent, CardHeader, CardTitle } from “@/components/ui/card”
export default async function RecruiterDashboard() {
const session = await getServerSession()
if (!session?.user?.email) {
redirect(“/auth/signin”)
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
include: {
company: true,
jobs: {
include: {
_count: {
select: { applications: true },
},
},
orderBy: { createdAt: “desc” },
take: 5,
},
},
})
if (!user || user.role !== “RECRUITER”) {
redirect(“/unauthorized”)
}
// 获取统计数据
const totalJobs = await prisma.job.count({
where: { recruiterId: user.id },
})
const totalApplications = await prisma.application.count({
where: {
job: {
recruiterId: user.id,
},
},
})
const pendingApplications = await prisma.application.count({
where: {
job: {
recruiterId: user.id,
},
status: “PENDING”,
},
})
return (
Recruiter Dashboard
Manage your job postings and applications
{/* Stats Cards */}
{totalJobs}
{totalApplications}
{pendingApplications}
{/* Recent Jobs */}
Recent Job Postings
{user.jobs.length === 0 ? (
No jobs posted yet
) : (
{job.title}
{job.location} • {job.type}
{job._count.applications} applications
))}
)}
)
}
求职者仪表盘:
// src/app/dashboard/page.tsx
import { getServerSession } from “next-auth”
import { redirect } from “next/navigation”
import { prisma } from “@/lib/db”
export default async function CandidateDashboard() {
const session = await getServerSession()
if (!session?.user?.email) {
redirect(“/auth/signin”)
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
include: {
applications: {
include: {
job: {
include: {
company: true,
},
},
},
orderBy: { createdAt: “desc” },
take: 10,
},
},
})
if (!user || user.role !== “CANDIDATE”) {
redirect(“/unauthorized”)
}
const stats = {
totalApplications: await prisma.application.count({
where: { candidateId: user.id },
}),
pending: await prisma.application.count({
where: { candidateId: user.id, status: “PENDING” },
}),
reviewed: await prisma.application.count({
where: { candidateId: user.id, status: “REVIEWED” },
}),
accepted: await prisma.application.count({
where: { candidateId: user.id, status: “ACCEPTED” },
}),
}
return (
My Dashboard
Track your job applications
{/* Stats */}
Total Applications
{stats.totalApplications}
Pending
{stats.pending}
Reviewed
{stats.reviewed}
Accepted
{stats.accepted}
{/* Applications List */}
Recent Applications
{user.applications.length === 0 ? (
You haven’t applied to any jobs yet.{” “}
Browse jobs
) : (
{app.job.title}
{app.job.company.name} • {app.job.location}
{app.status}
Applied {new Date(app.createdAt).toLocaleDateString()}
))}
)}
)
}
五、高级功能与优化
5.1 实时通知系统
使用WebSockets实现实时通知(当招聘者查看申请时通知求职者)。
使用Next.js API Routes + WebSocket:
// src/app/api/notifications/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { prisma } from “@/lib/db”
// 获取用户通知
export async function GET(request: NextRequest) {
const session = await getServerSession()
if (!session?.user?.email) {
return NextResponse.json({ error: “Unauthorized” }, { status: 401 })
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
select: { id: true },
})
if (!user) {
return NextResponse.json({ error: “User not found” }, { status: 404 })
}
const notifications = await prisma.notification.findMany({
where: {
userId: user.id,
read: false,
},
orderBy: { createdAt: “desc” },
take: 20,
})
return NextResponse.json({ notifications })
}
// 创建通知
export async function POST(request: NextRequest) {
const session = await getServerSession()
if (!session?.user?.email) {
return NextResponse.json({ error: “Unauthorized” }, { status: 401 })
}
const { userId, message, type, url } = await request.json()
const notification = await prisma.notification.create({
data: {
userId,
message,
type,
url,
},
})
// 这里可以触发WebSocket推送
// await pusher.trigger(`user-${userId}`, ‘new-notification’, notification)
return NextResponse.json({ notification }, { status: 201 })
}
前端通知组件:
// src/components/NotificationBell.tsx
“use client”
import { useEffect, useState } from “react”
import { useSession } from “next-auth/react”
import { Bell } from “lucide-react”
interface Notification {
id: string
message: string
type: string
url?: string
createdAt: Date
}
export default function NotificationBell() {
const { data: session } = useSession()
const [notifications, setNotifications] = useState
const [unreadCount, setUnreadCount] = useState(0)
const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
if (!session) return
// 初始加载
fetchNotifications()
// 轮询检查新通知(生产环境应使用WebSocket)
const interval = setInterval(fetchNotifications, 30000)
return () => clearInterval(interval)
}, [session])
const fetchNotifications = async () => {
try {
const res = await fetch(“/api/notifications”)
const data = await res.json()
setNotifications(data.notifications)
setUnreadCount(data.notifications.length)
} catch (error) {
console.error(“Failed to fetch notifications”)
}
}
const markAsRead = async (id: string) => {
try {
await fetch(`/api/notifications/${id}/read`, { method: “POST” })
setNotifications(prev => prev.filter(n => n.id !== id))
setUnreadCount(prev => Math.max(0, prev – 1))
} catch (error) {
console.error(“Failed to mark as read”)
}
}
if (!session) return null
return (
{isOpen && (
) : (
notifications.map((notif) => (
if (notif.url) window.location.href = notif.url
markAsRead(notif.id)
setIsOpen(false)
}}
>
{notif.message}
{new Date(notif.createdAt).toLocaleTimeString()}
))
)}
)}
)
}
5.2 文件上传与简历管理
使用AWS S3或Cloudinary进行文件存储:
// src/app/api/upload/route.ts
import { NextRequest, NextResponse } from “next/server”
import { getServerSession } from “next-auth”
import { S3Client, PutObjectCommand } from “@aws-sdk/client-s3”
import { getSignedUrl } from “@aws-sdk/s3-request-presigner”
const s3 = new S3Client({
region: process.env.AWS_REGION!,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
},
})
export async function POST(request: NextRequest) {
const session = await getServerSession()
if (!session?.user?.email) {
return NextResponse.json({ error: “Unauthorized” }, { status: 401 })
}
const { fileName, fileType } = await request.json()
// 生成唯一的文件名
const key = `resumes/${session.user.id}/${Date.now()}-${fileName}`
const command = new PutObjectCommand({
Bucket: process.env.AWS_S3_BUCKET!,
Key: key,
ContentType: fileType,
ACL: “public-read”,
})
try {
const signedUrl = await getSignedUrl(s3, command, { expiresIn: 60 })
return NextResponse.json({
success: true,
url: signedUrl,
key,
publicUrl: `https://${process.env.AWS_S3_BUCKET}.s3.${process.env.AWS_REGION}.amazonaws.com/${key}`,
})
} catch (error) {
return NextResponse.json(
{ error: “Failed to generate upload URL” },
{ status: 500 }
)
}
}
前端上传组件:
// src/components/ResumeUpload.tsx
“use client”
import { useState } from “react”
import { UploadCloud, FileText, X } from “lucide-react”
import { useSession } from “next-auth/react”
interface ResumeUploadProps {
onUploadComplete: (url: string) => void
currentResume?: string
}
export default function ResumeUpload({ onUploadComplete, currentResume }: ResumeUploadProps) {
const { data: session } = useSession()
const [uploading, setUploading] = useState(false)
const [progress, setProgress] = useState(0)
const [error, setError] = useState
const handleFileSelect = async (e: React.ChangeEvent
const file = e.target.files?.[0]
if (!file) return
// 验证文件类型和大小
if (!file.type.includes(“pdf”) && !file.type.includes(“doc”)) {
setError(“Please upload a PDF or Word document”)
return
}
if (file.size > 5 * 1024 * 1024) {
setError(“File size must be less than 5MB”)
return
}
setUploading(true)
setError(null)
try {
// 1. 获取预签名URL
const res = await fetch(“/api/upload”, {
method: “POST”,
headers: { “Content-Type”: “application/json” },
body: JSON.stringify({
fileName: file.name,
fileType: file.type,
}),
})
if (!res.ok) throw new Error(“Failed to get upload URL”)
const { url, publicUrl } = await res.json()
// 2. 上传到S3
const xhr = new XMLHttpRequest()
xhr.upload.addEventListener(“progress”, (e) => {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100)
setProgress(percent)
}
})
xhr.addEventListener(“load”, () => {
if (xhr.status === 200) {
onUploadComplete(publicUrl)
setUploading(false)
setProgress(0)
} else {
throw new Error(“Upload failed”)
}
})
xhr.addEventListener(“error”, () => {
throw new Error(“Network error”)
})
xhr.open(“PUT”, url)
xhr.setRequestHeader(“Content-Type”, file.type)
xhr.send(file)
} catch (err) {
setError(err instanceof Error ? err.message : “Upload failed”)
setUploading(false)
setProgress(0)
}
}
const removeResume = () => {
onUploadComplete(“”)
}
return (
{currentResume ? (
Resume uploaded
) : (
)}
{error && (
{error}
)}
)
}
5.3 搜索引擎优化(SEO)
页面元数据:
// src/app/jobs/[id]/page.tsx
import { Metadata } from “next”
import { prisma } from “@/lib/db”
interface PageProps {
params: { id: string }
}
// 生成静态元数据
export async function generateMetadata({ params }: PageProps): Promise
const job = await prisma.job.findUnique({
where: { id: params.id },
include: { company: true },
})
if (!job) {
return {
title: “Job Not Found”,
}
}
return {
title: `${job.title} at ${job.company.name} – Job Platform`,
description: job.description.substring(0, 160),
openGraph: {
title: `${job.title} at ${job.company.name}`,
description: job.description.substring(0, 160),
type: “website”,
url: `https://yourdomain.com/jobs/${job.id}`,
images: job.company.logo ? [job.company.logo] : [],
},
twitter: {
card: “summary_large_image”,
title: `${job.title} at ${job.company.name}`,
description: job.description.substring(0, 160),
},
}
}
// 生成静态页面(SSG)
export async function generateStaticParams() {
const jobs = await prisma.job.findMany({
where: { status: “ACTIVE” },
select: { id: true },
take: 100, // 生成前100个职位页面
})
return jobs.map((job) => ({
id: job.id,
}))
}
export default async function JobDetailPage({ params }: PageProps) {
// 页面组件实现…
}
Sitemap生成:
// src/app/sitemap.ts
import { MetadataRoute } from “next”
import { prisma } from “@/lib/db”
export default async function sitemap(): Promise
const baseUrl = “https://yourdomain.com”
// 静态页面
const staticPages = [
{ url: baseUrl, lastModified: new Date() },
{ url: `${baseUrl}/jobs`, lastModified: new Date() },
{ url: `${baseUrl}/about`, lastModified: new Date() },
{ url: `${baseUrl}/contact`, lastModified: new Date() },
]
// 动态职位页面
const jobs = await prisma.job.findMany({
where: { status: “ACTIVE” },
select: { id: true, updatedAt: true },
take: 1000,
})
const jobPages = jobs.map((job) => ({
url: `${baseUrl}/jobs/${job.id}`,
lastModified: job.updatedAt,
}))
return […staticPages, …jobPages]
}
Robots.txt:
// src/app/robots.ts
import { MetadataRoute } from “next”
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: “*”,
allow: “/”,
disallow: [“/admin/”, “/recruiter/”, “/api/auth/”],
},
sitemap: “https://yourdomain.com/sitemap.xml”,
}
}
5.4 性能优化
1. 图片优化:
// src/components/CompanyLogo.tsx
import Image from “next/image”
interface CompanyLogoProps {
src?: string
name: string
size?: number
}
export default function CompanyLogo({ src, name, size = 48 }: CompanyLogoProps) {
if (!src) {
// 显示占位符
return (
{name.charAt(0).toUpperCase()}
)
}
return (
)
}
2. 数据获取优化:
// 使用React Query进行数据缓存
“use client”
import { useQuery } from “@tanstack/react-query”
import { useSession } from “next-auth/react”
export function useUserJobs() {
const { data: session } = useSession()
return useQuery({
queryKey: [“user-jobs”, session?.user?.id],
queryFn: async () => {
const res = await fetch(“/api/jobs/my”)
if (!res.ok) throw new Error(“Failed to fetch jobs”)
return res.json()
},
enabled: !!session,
staleTime: 1000 * 60 * 5, // 5分钟缓存
})
}
3. 代码分割与懒加载:
// src/app/jobs/page.tsx
import { Suspense, lazy } from “react”
import JobSearch from “@/components/job/JobSearch”
// 懒加载重型组件
const JobList = lazy(() => import(“@/components/job/JobList”))
const JobFilters = lazy(() => import(“@/components/job/JobFilters”))
export default function JobsPage() {
return (
}>
}>