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

AWS Amplify部署SSR模式Next.js应用报503,提示缺失@grpc/grpc-js模块

根因分析

该503错误由AWS Amplify Next.js SSR构建流程的依赖裁剪逻辑和Next.js打包的tree shaking规则叠加导致:

  • @grpc/grpc-js是Firebase Firestore的可选依赖,默认不会被包管理器强制安装,即便手动安装后,Amplify构建SSR对应的Lambda包时也会默认裁剪未被顶层代码显式引用的间接依赖
  • Next.js的SSR打包逻辑默认不会将间接可选依赖纳入最终运行时包,即便是手动安装的依赖,只要没有被顶层代码显式引用,也会被webpack移除,导致Lambda运行时找不到模块
修复步骤

1. 调整Next.js打包配置

在项目根目录的next.config.js中添加配置,强制将相关依赖纳入SSR运行时:

  • Next.js 13.4及以上版本(配置已稳定):
/** @type {import('next').NextConfig} */
const nextConfig = {
  serverExternalPackages: ['@grpc/grpc-js', '@firebase/firestore']
}

module.exports = nextConfig
  • Next.js 12.2~13.3版本:
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverComponentsExternalPackages: ['@grpc/grpc-js', '@firebase/firestore']
  }
}

module.exports = nextConfig

2. 调整Amplify构建配置

修改项目根目录的amplify.yml,安装依赖时强制包含可选依赖,避免被裁剪:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        # 根据你的包管理器选择对应命令
        - npm install --include=optional
        # - yarn install --optional
        # - pnpm install --no-optional=false
        - npm ls @grpc/grpc-js # 构建日志输出确认依赖已安装
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

3. (可选,仅使用pnpm时需要)调整pnpm配置

在项目根目录的.npmrc中添加以下配置,确保依赖被提升到顶层node_modules:

public-hoist-pattern[]=@grpc/grpc-js

完成所有配置变更后重新触发Amplify部署即可解决该问题。


内容的提问来源于stack exchange,提问作者Fanis Mahmalat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:06