# 部署说明 ## 解决 "Failed to find Server Action" 错误 在 PM2 自托管 Next.js 时,若出现以下错误: ``` Error: Failed to find Server Action. This request might be from an older or newer deployment. ``` **原因**:Next.js 为 Server Actions 使用加密密钥,每次构建会重新生成。部署后客户端可能仍缓存旧版本 JS,导致请求的 action ID 与服务器不匹配。 **解决方案**:在**构建时**设置固定加密密钥 `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY`,使多次部署使用相同密钥。 ### 步骤 1. **生成密钥**(仅需执行一次,之后复用同一密钥): ```bash node scripts/generate-encryption-key.js ``` 2. **在构建前设置环境变量**: ```bash export NEXT_SERVER_ACTIONS_ENCRYPTION_KEY="<上一步输出的 base64 字符串>" pnpm build ``` 或在 `.env` / `.env.production` 中添加: ``` NEXT_SERVER_ACTIONS_ENCRYPTION_KEY= ``` 3. **重新构建并重启**: ```bash pnpm build pm2 restart vip ``` 4. **建议用户清除缓存**:部署后若仍有问题,可让用户执行硬刷新(Ctrl+Shift+R)或清除浏览器缓存。 --- ## PM2 部署流程 ```bash # 1. 安装依赖 pnpm install # 2. 设置 NEXT_SERVER_ACTIONS_ENCRYPTION_KEY 后构建 export NEXT_SERVER_ACTIONS_ENCRYPTION_KEY="你的密钥" pnpm build # 3. 启动 pnpm start # 或使用 PM2 pm2 start npm --name vip -- start ```