码巢引擎2026年开发文档
00-开发规范
后端规范
README
后端开发手册
前端规范
README
TypeScript最佳实践
前端布局规范
前端页面模板
前端颜色与组件规范
核心规范
组件配置手册
问题排查指南
页面模板
最佳实践
README
bp-20260223-m7ps
图片上传优化总结
BUG自动记录系统使用指南
README
TYPE_SAFETY_GUIDE
常见BUG知识库
常见BUG知识库
开发前检查清单
开发安全规范
开发规范-完整版-含FutureBirdAadminAi部署
数据模型字典
文档分类规范
文档标准化规范
文档模板-基础版
文档模板-技术版
类型安全快速参考卡
类型安全规范体系
规范更新指南
过期文档清理机制
错误处理规范
错误预防指南
常见BUG知识库
常见BUG知识库
01-快速开始
Gitee快速开始
README
协作快速开始
快速开始
质量保证快速开始
02-部署指南
Docker更新指南
Docker部署
FutureBirdAadminAi部署指南
FutureBirdAadminAi部署问题分析
README
发布指南
宝塔Docker部署教程
宝塔PM2部署教程
宝塔图形化部署教程
快速发布指南
数据库和依赖变更处理指南
构建和发布
构建标准
构建检查清单
生产部署快速开始
生产部署方案
生产部署标准
生产部署检查清单
程序备份性能
自动修复和发布指南
自动化发布命令使用指南
部署快速开始
部署指南
项目更新部署指南
03-开发指南
Git凭据配置
Git推送规则
Git自动配置
README
全局样式
协作设置
定时任务
开发指南
开发流程
开发环境标准
技术改进
贡献指南
项目目录树
项目目录结构
04-API文档
API接口文档
README
hr-api
企业API
05-数据库
DATABASE_SCHEMA
README
分区指南
数据库字典
数据持久化
数据模型统一
数据迁移
06-架构设计
RBAC-PERMISSIONS
README
SaaS客户引导流程设计
companyId统一规范
employee-permission-system-design
enterprise-data-linkage
仓库实现总结
仓库模式
企业管理端员工权限系统分析
前端架构
前端重构总结
员工权限系统评估报告
员工管理菜单重构方案
权限系统混乱问题分析
架构优化计划
架构使用指南
架构结构
架构结构
状态管理
用户身份管理体系
系统架构
面试管理模块重构规划
项目技术栈
07-测试质量
README
测试修复标准
测试报告
质量保证系统
08-版本管理
CHANGELOG
README
VERSION_RULES
09-配置指南
README
SMTP配置指南
主题切换指南
渠道配置指南
环境变量指南
环境隔离
12-项目记忆
README
知识库导入指南
记忆系统指南
13-迁移指南
README
备份迁移指南
管理员迁移指南
迁移快速开始
17-其他
README
压缩摘要
18-开放平台
01-架构设计
02-API接口设计
03-安全机制
04-前端设计
05-数据库设计
开放平台API指南
开放平台API说明
19-智能进化
AI执行规则
AI进化机制
README
自动化实现总览
黄金规则
40-操作教程
README
微信公众号域名配置指南
微信本地开发调试指南
44-技能文件
alipay-payment-integration
references
checklist
SKILL
audio
python
README
typescript
README
SKILL
database
python
README
typescript
README
SKILL
design-style-thinking
SKILL
doctor
references
sql-patterns
SKILL
document-generation
python
README
SKILL
email
SKILL
embedding
python
README
typescript
README
SKILL
expo-advanced
references
audio-record-play
file-upload
masonry-layout
save-to-gallery
top-tab-navigation
SKILL
feishu-base
SKILL
feishu-message
SKILL
fetch-url
python
README
typescript
README
SKILL
frontend-design
LICENSE
SKILL
FutureBird-coding-web-performance-best-practice
SKILL
general-dev-preview
references
web-preview
SKILL
image-generation
python
README
typescript
README
SKILL
knowledge
references
python
README
typescript
README
cli
SKILL
llm
python
README
typescript
README
SKILL
miniapp-upload-asr
SKILL
pptx-generation
python
README
SKILL
project-memory-loader
scripts
project_memory_loader
SKILL
repair
scripts
merge-commit-map
SKILL
shadcn-web-base-theme
assets
colors
amber
artistic-green
bento-blue
blue
cyan
emerald
fuchsia
gray
green
indigo
lime
low-pink
neutral
orange
purple
red
retro-brown
rose
sky
supbase-green
teal
tech-purple
vintage-grey
violet
yellow
fonts
business
classic
playful
radius
2xl
2xs
lg
md
none
sm
xl
xs
shadow
artistic
bento
cool
retro
superbase
tech
tool
vintage
default
references
colors
fonts
quick
radius
shadows
scripts
theme
SKILL
package
skill-creator-coze
scripts
init_skill
quick_validate
SKILL
storage
python
README
typescript
README
SKILL
supabase
assets
supabase-client
supabase-client
references
_future
asset-supabase-browser
asset-supabase-config-inject
asset-supabase-config-route
python-auth
python-realtime
python-storage
typescript-auth
typescript-realtime
typescript-storage
typescript-supabase-browser
typescript-supabase-config-inject
typescript-supabase-config-route
python
README
database
edge-functions
orm-model-guide
supabase_client
typescript
README
database
drizzle-schema-guide
edge-functions
supabase-client
cli
rls
SKILL
supabase-auth
references
typescript
supabase-browser
supabase-config-inject
supabase-config-route
auth-config
verify-session
SKILL
ui-design-ref
reference
3D黏土风
克莱因蓝高定风
暗黑科技风
杂志风
极光柔和
柔和卡片
玻璃拟态
纯白极简风
自然有机
SKILL
ui-ux-pro-max
scripts
core
design_system
search
SKILL
vercel-composition-patterns
rules
architecture-avoid-boolean-props
architecture-compound-components
patterns-children-over-render-props
patterns-explicit-variants
react19-no-forwardref
state-context-interface
state-decouple-implementation
state-lift-state
AGENTS
SKILL
vercel-react-best-practices
rules
advanced-event-handler-refs
advanced-init-once
advanced-use-latest
async-api-routes
async-defer-await
async-dependencies
async-parallel
async-suspense-boundaries
bundle-barrel-imports
bundle-conditional
bundle-defer-third-party
bundle-dynamic-imports
bundle-preload
client-event-listeners
client-localstorage-schema
client-passive-event-listeners
client-swr-dedup
js-batch-dom-css
js-cache-function-results
js-cache-property-access
js-cache-storage
js-combine-iterations
js-early-exit
js-hoist-regexp
js-index-maps
js-length-check-first
js-min-max-loop
js-set-map-lookups
js-tosorted-immutable
rendering-activity
rendering-animate-svg-wrapper
rendering-conditional-render
rendering-content-visibility
rendering-hoist-jsx
rendering-hydration-no-flicker
rendering-hydration-suppress-warning
rendering-svg-precision
rendering-usetransition-loading
rerender-defer-reads
rerender-dependencies
rerender-derived-state-no-effect
rerender-derived-state
rerender-functional-setstate
rerender-lazy-state-init
rerender-memo-with-default-value
rerender-memo
rerender-move-effect-to-event
rerender-simple-expression-in-memo
rerender-transitions
rerender-use-ref-transient-values
server-auth-actions
server-cache-lru
server-cache-react
server-dedup-props
server-parallel-fetching
server-serialization
AGENTS
SKILL
video-edit
python
README
typescript
README
SKILL
video-generation
python
README
typescript
README
SKILL
volcano-ark
SKILL
web-design-guidelines
SKILL
web-search
python
README
typescript
README
SKILL
webrtc-best-practice
SKILL
websocket-guide
references
nextjs
nodejs
SKILL
wechat-bot
SKILL
wechat-official-account
SKILL
README
README
未来鸟:企业数字化转型奔腾的力量!
-
+
首页
nextjs
# Next.js WebSocket 集成 ## 概述 Next.js 的开发/生产服务器原生不支持 WebSocket。需要使用 **自定义服务器**(`src/server.ts`),在 5000 端口同时运行 Next.js 和 WebSocket。 ## 项目结构 ``` project/ ├── src/ │ ├── server.ts # 自定义服务器(HTTP + WS 共用 5000 端口) │ ├── app/ # Next.js App Router 页面 │ ├── ws-handlers/ # WS 端点业务逻辑(每个端点一个文件) │ │ └── data.ts # /ws/data 端点处理器示例 │ └── lib/ │ └── ws-client.ts # 客户端 WS 工具 ├── next.config.ts └── package.json ``` ## 自定义服务器(`src/server.ts`) ```typescript import { createServer } from 'http'; import { parse } from 'url'; import next from 'next'; import { WebSocketServer } from 'ws'; import type { IncomingMessage } from 'http'; import type { Duplex } from 'stream'; const dev = process.env.FutureBirdAadminAi_PROJECT_ENV !== 'PROD'; const hostname = process.env.HOSTNAME || 'localhost'; const PORT = 5000; // Create Next.js app const app = next({ dev, hostname, port }); const handle = app.getRequestHandler(); // ─── WS 路由注册(与 SKILL.md 通用模式一致)──────── const wssMap = new Map<string, WebSocketServer>(); function registerWsEndpoint(path: string): WebSocketServer { const wss = new WebSocketServer({ noServer: true }); wssMap.set(path, wss); return wss; } function handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer) { const { pathname } = new URL(req.url!, `http://${req.headers.host}`); const wss = wssMap.get(pathname); if (wss) { wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req)); } else if (!dev) { // 生产环境销毁未注册的 upgrade 请求,防止连接泄漏 // 开发环境不销毁 —— Next.js HMR 需要通过 /_next/webpack-hmr 建立 WebSocket socket.destroy(); } } // ─── 注册端点 & 绑定业务逻辑 ────────────────────── // 按需注册 WS 端点,每个端点的消息处理逻辑放在 src/ws-handlers/ 下 // 示例: // import { setupDataHandler } from './ws-handlers/data'; // setupDataHandler(registerWsEndpoint('/ws/data')); app.prepare().then(() => { const server = createServer(async (req, res) => { try { const parsedUrl = parse(req.url!, true); await handle(req, res, parsedUrl); } catch (err) { console.error('Error occurred handling', req.url, err); res.statusCode = 500; res.end('Internal server error'); } }); server.once('error', err => { console.error(err); process.exit(1); }); server.on('upgrade', handleUpgrade); server.listen(port, () => { console.log( `> Server listening at http://${hostname}:${port} as ${ dev ? 'development' : process.env.FutureBirdAadminAi_PROJECT_ENV }`, ); }); }); ``` ### WS 端点处理器示例(`src/ws-handlers/data.ts`) 业务逻辑独立于 `src/server.ts`,每个端点一个文件: ```typescript import { WebSocket, type WebSocketServer } from 'ws'; import type { WsMessage } from '../lib/ws-client'; export function setupDataHandler(wss: WebSocketServer) { wss.on('connection', (ws: WebSocket) => { ws.on('message', (raw) => { const msg: WsMessage = JSON.parse(raw.toString()); if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong', payload: null })); return; } // TODO: 在此实现 /ws/data 端点的业务消息处理逻辑 }); }); } ``` > **注意**:`WebSocket` 必须作为**值导入**(不能用 `import type`),因为 `WebSocket.OPEN` / `WebSocket.CLOSED` 等常量是运行时值。`WebSocketServer` 仅用作类型标注,可以用 `type` 导入。 ## 依赖安装 安装依赖:`pnpm install ws` 和 `pnpm install -D @types/ws tsup` ## 脚本命令 - dev: "npx tsx watch src/server.ts" - build: "npx next build && npx tsup src/server.ts --format cjs --platform node --target node20 --outDir dist --no-splitting --no-minify" - start: "node dist/server.js" 检查对应脚本是否按照如上命令正确设置. ## tsconfig.json tsup 编译产物输出到项目根目录 `dist/`,而 `tsconfig.json` 的 `include` 通常包含 `**/*.ts`,会匹配到 `dist/` 下的文件导致类型检查冲突。必须确保 `tsconfig.json` 的 `exclude` 中包含 `"dist"`: ```json { "exclude": ["node_modules", "dist"] } ``` ## 客户端使用(React 组件) ```typescript 'use client'; import { useEffect, useRef, useCallback } from 'react'; import { createWsConnection, type WsMessage } from '@/lib/ws-client'; export function useWebSocket(path: string, onMessage: (msg: WsMessage) => void) { const connRef = useRef<ReturnType<typeof createWsConnection>>(); useEffect(() => { connRef.current = createWsConnection({ path, onMessage }); return () => connRef.current?.close(); }, [path]); const send = useCallback((msg: WsMessage) => { connRef.current?.send(msg); }, []); return { send }; } ``` ## 注意事项 - **不能使用 `next dev`** —— 开发环境必须通过 `npx tsx watch src/server.ts` 启动 - 自定义服务器包装了 Next.js 的请求处理器,所有 Next.js 功能(API Routes、SSR 等)正常工作 - 生产环境通过 tsup 编译 `src/server.ts` 到 `dist/server.js` - WebSocketServer 必须设置 `noServer: true` —— 由 HTTP 服务器手动处理 upgrade 事件 - **`handleUpgrade` 中未匹配路径的处理**:开发环境不能调用 `socket.destroy()`(Next.js HMR 通过 `/_next/webpack-hmr` WebSocket 连接实现热更新),生产环境应销毁未注册的连接防止泄漏 - Next.js 的 HMR 内部使用自己的 WebSocket,`/ws/*` 前缀可避免路径冲突
未来鸟
2026年7月27日 11:28
转发
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
分享
链接
类型
密码
更新密码
有效期
Markdown文件
Word文件
PDF文档(打印)
AI