通过AWS CDK部署Next.js至Amplify Hosting后页面无法访问求助
解决Amplify Hosting部署Next.js SSR后404问题
针对你的Next.js SSR(启用App Router)通过AWS CDK+Amplify Hosting部署后出现页面无法找到的问题,可从以下几个方向排查修复:
1. 修正构建规范的目录一致性问题
Amplify的每个构建阶段会默认回到项目根目录,你在preBuild中执行了cd frontend,但build阶段的命令并未确保在frontend目录执行,导致构建可能在错误路径下运行。修改build阶段命令:
build: { commands: [ 'cd frontend', 'npm run build' ], },
或者合并为单条命令避免目录切换问题:
build: { commands: [ 'cd frontend && npm run build' ], },
2. 适配Next.js SSR的构建产物配置
Amplify Hosting需要完整的Next.js SSR产物(包括服务端代码),仅配置frontend artifacts不足以支撑SSR运行。需在build spec中添加server配置段,指定服务端依赖与启动路径:
buildSpec: codebuild.BuildSpec.fromObjectToYaml({ version: '1.0', frontend: { phases: { preBuild: { commands: [ 'cd frontend', 'npm install' ], }, build: { commands: [ 'cd frontend && npm run build' ], }, }, artifacts: { baseDirectory: 'frontend/.next', files: ['**/*'], }, staticAssets: { baseDirectory: 'frontend/public', files: ['**/*'] } }, // 新增server配置,适配SSR运行 server: { phases: { build: { commands: [ 'cd frontend && npm install' ] } }, artifacts: { baseDirectory: 'frontend', files: [ 'package.json', '.next/**/*', 'node_modules/**/*' ] } }, appRoot: 'frontend', runtimeVersion: { nodejs: 18 // 使用Next.js 13+支持的Node.js版本(18.x或20.x) } })
3. 优化Next.js配置适配Amplify SSR
Next.js 13+ App Router推荐使用output: 'standalone'生成轻量化的独立服务端产物,更适配Amplify的部署环境:
/** @type {import('next').NextConfig} */ const nextConfig = { eslint: { ignoreDuringBuilds: true, }, typescript: { ignoreBuildErrors: true, }, images: { unoptimized: true, }, distDir: '.next', output: 'standalone', // 生成独立服务端产物 experimental: { appDir: true, }, } export default nextConfig
使用该配置后,需调整build spec的server.artifacts.baseDirectory为frontend/.next/standalone,确保部署的是独立服务端包。
4. 排查部署日志定位问题
登录AWS Amplify控制台,进入对应应用:
- 查看构建日志,确认依赖安装、项目构建无报错
- 查看部署日志,验证所有必要文件(如
.next/server、package.json)已上传 - 查看访问日志,确认404请求的具体路径,排查是否是路由配置问题
5. 确认Amplify SSR运行时设置
在Amplify控制台的「应用设置」→「常规」→「应用设置」中:
- 确认运行时设置为Node.js,版本为18.x或20.x(Next.js 13+要求)
- 确保Amplify已识别应用为SSR类型(若使用自定义build spec,需手动配置runtime)
内容的提问来源于stack exchange,提问作者Zen Biz
相关产品推荐
相关产品推荐

