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

Next.js 14生产环境调用AWS Amplify Gen2数据接口报错排查

问题原因分析

这个生产环境独有的报错,核心是client.models.Posts在生产构建后变为undefined,常见诱因有以下几点:

  1. 树摇优化误删模型代码:Next.js生产构建的树摇机制可能因Schema是类型导入(import type),将其判定为非实际依赖,误删Amplify生成的模型实例代码。
  2. 全局客户端初始化时机异常:在全局作用域提前生成client,会在Next.js静态构建阶段执行,此时Amplify配置未完全加载,导致模型未正确初始化。
  3. 手动请求头与Amplify逻辑冲突:手动设置x-api-key头,可能和AmplifyapiKey认证模式的自动处理逻辑冲突,引发客户端内部状态异常。
解决方案

1. 调整客户端生成时机到函数内部

把generateClient调用移到fetchPosts函数内部,避免全局初始化在生产构建阶段的异常:

import { generateClient } from 'aws-amplify/data';
import type { Schema } from '@/amplify/data/resource';

interface Post {
    createdAt: string;
    imageUrl: string;
    slug: string;
    titleEn: string;
    titlePt: string;
    titleEs: string;
}

async function fetchPosts() {
    const apiKey = process.env.NEXT_PUBLIC_API_KEY;

    if (!apiKey) {
        console.error("API key is missing");
        return [];
    }

    // 函数内部生成客户端,确保配置加载完成
    const client = generateClient<Schema>({
        authMode: 'apiKey',
        apiKey: apiKey // 直接传入apiKey,Amplify会自动处理请求头
    });

    const { data: posts, errors } = await client.models.Posts.list();

    if (errors) {
        console.error("Failed to fetch posts:", errors);
        return [];
    }

    return posts as Post[];
}

2. 确保Amplify代码生成在构建前执行

检查package.json的build脚本,先执行Amplify代码生成,再进行Next.js构建:

{
  "scripts": {
    "dev": "next dev",
    "build": "amplify codegen && next build",
    "start": "next start",
    "lint": "next lint"
  }
}

3. 添加Next.js转译配置

在next.config.js中把aws-amplify加入转译包列表,避免生产构建时的编译兼容性问题:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['aws-amplify'],
};

module.exports = nextConfig;

4. 升级Amplify依赖到最新版本

旧版AWS Amplify Gen2可能存在Next.js 14生产构建的兼容性bug,执行命令升级:

npm update aws-amplify @aws-amplify/data

5. 验证Schema导入正确性

确认@/amplify/data/resource路径无误,且Amplify生成的Schema类型包含Posts模型。可查看.amplify/generated/data目录下的生成代码,检查Posts模型定义是否存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:42:36