You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vercel部署Next.js应用时Playwright浏览器启动失败求助

问题原因及解决办法

核心原因

Vercel的构建环境与运行环境完全隔离:构建阶段通过npx playwright install安装的浏览器会存放在构建环境的缓存目录(如/home/sbx_user1051/.cache/ms-playwright),但该目录不会被打包部署到运行环境,导致运行时找不到浏览器可执行文件。

解决办法

1. 将浏览器安装到项目目录(推荐)

修改Vercel构建命令,指定浏览器安装到项目内的文件夹,确保该文件夹被纳入部署产物:

next build && npx playwright install --dir ./playwright-browsers

然后在代码中指定浏览器路径启动:

const { chromium } = require('playwright');

// 动态获取浏览器路径(适配版本变化)
const browserPath = chromium.executablePath({ paths: ['./playwright-browsers'] });
const browser = await chromium.launch({
  executablePath: browserPath,
  headless: true,
  args: ['--no-sandbox', '--disable-dev-shm-usage'] // 适配Serverless环境的必要参数
});

2. 配置环境变量指定缓存路径

在Vercel项目的环境变量中添加:

PLAYWRIGHT_BROWSERS_PATH=0

该变量会让Playwright将浏览器安装到项目的node_modules/playwright/.cache目录(该目录会被部署),构建命令保持next build && npx playwright install即可。

3. 补充系统依赖

Vercel运行环境可能缺少Chromium所需的系统库,可在构建命令中提前安装:

sudo apt-get update && sudo apt-get install -y libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libasound2 && next build && npx playwright install --dir ./playwright-browsers

4. 优化浏览器启动参数

Serverless环境资源有限,启动浏览器时需添加适配参数:

const browser = await chromium.launch({
  headless: true,
  args: [
    '--no-sandbox',
    '--disable-setuid-sandbox',
    '--disable-dev-shm-usage',
    '--single-process',
    '--no-zygote'
  ]
});

内容的提问来源于stack exchange,提问作者Nishant Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:20:10