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

如何将NextJS 13部署到AWS Lambda?SSR模式部署是否可行?

Next.js 部署到 AWS Lambda 相关问题解答

1. Next.js 应用能否部署至 AWS Lambda?可行的操作方法是什么?

可以部署。主流实现方式分为两种:借助 Serverless Framework 插件快速部署,或是基于 Next.js 的 standalone 输出模式,配合 AWS 工具手动部署。

操作方法(Serverless Framework 为例)

  • 初始化 Serverless 项目:serverless create --template aws-nodejs --name nextjs-lambda
  • 安装依赖:npm install next react react-dom serverless-nextjs-plugin
  • 编辑 serverless.yml 配置,指定 Next.js 目录并启用插件:
    service: nextjs-lambda
    frameworkVersion: '3'
    plugins:
      - serverless-nextjs-plugin
    custom:
      nextjs:
        dir: ./
    provider:
      name: aws
      runtime: nodejs18.x
      region: us-east-1
    
  • 执行部署:serverless deploy

手动部署方式(Next.js Standalone)

  • 在 next.config.js 中添加 output: 'standalone' 配置
  • 执行 npm run build,生成 .next/standalone 可执行目录
  • 将 .next/standalone、.next/static、public 目录打包为 ZIP 文件
  • 登录 AWS 控制台,创建 Lambda 函数并上传 ZIP 包,配置 API Gateway 作为触发器,将所有请求路由到 Lambda

2. Next.js 13 以 SSR 模式部署到 AWS Lambda 的方法

Next.js 13 无论是 Pages Router(基于 getServerSideProps)还是 App Router(基于 Server Components/异步组件)的 SSR 模式,都能部署到 AWS Lambda,具体步骤如下:

前置配置

在 next.config.js 中启用 standalone 输出,确保 SSR 代码能被 Lambda 正确执行:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
  experimental: {
    appDir: true, // 使用 App Router 时需开启
  },
};

module.exports = nextConfig;

方式一:Serverless Framework 部署

  1. 安装依赖:npm install serverless-nextjs-plugin
  2. 编写 serverless.yml 配置,确保 SSR 请求被 Lambda 处理:
service: nextjs13-ssr-lambda
frameworkVersion: '3'
plugins:
  - serverless-nextjs-plugin
custom:
  nextjs:
    dir: ./
    overrideLambda: true
provider:
  name: aws
  runtime: nodejs18.x
  region: us-east-1
  memorySize: 1024 # SSR 建议至少分配 1GB 内存
  timeout: 10 # 按需调整超时时间
  1. 执行部署:serverless deploy

方式二:AWS CDK 部署

  1. 打包 Next.js 项目:npm run build
  2. 用 AWS CDK 定义 Lambda 函数,指定部署包为 .next/standalone 等目录的压缩包
  3. 配置 API Gateway 作为 Lambda 触发器,设置通配符路由(/*)转发所有请求
  4. 部署 CDK 栈:cdk deploy

关键注意事项

  • SSR 模式下 Lambda 需分配足够资源,建议内存≥1GB、超时≥10秒
  • 确保 Lambda 执行角色拥有必要权限(如访问 S3 存储静态资源、调用其他 AWS 服务等)
  • App Router 的 Server Components 默认在 Lambda 端运行,无需额外配置,但要避免在 Server Components 中调用浏览器专属 API

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:42:12