Next.js Discord

Discord Forum

Next.js App works in development (npm run dev) but fails in production (npm run start) with AWS Ampl

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
I'm working on a Next.js 14 application that uses AWS Amplify Gen 2 for data fetching. Everything works as expected when I run the app in development mode using npm run dev. However, when I switch to production mode with npm run build followed by npm run start, I encounter a TypeError related to AWS Amplify's data fetching.

The specific error is: TypeError: Cannot read properties of undefined (reading 'list'). This occurs when trying to fetch data from AWS Amplify in my fetchPosts function.

Here's the relevant part of my code:

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

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

const client = generateClient<Schema>({
    authMode: 'apiKey'
});

async function fetchPosts() {
    console.log(process.env.NEXT_PUBLIC_API_KEY); // This logs the API key correctly
    const apiKey = process.env.NEXT_PUBLIC_API_KEY;

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

    const { data: posts, errors } = await client.models.Posts.list({
        authMode: 'apiKey',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': apiKey
        }
    });

    return posts as Post[];
}

// ... rest of the code ...


The error suggests an issue with accessing the list method, but only in the production build. The environment variable NEXT_PUBLIC_API_KEY is correctly set and logged to the console, so it doesn't seem to be an issue with missing environment variables.

However, the issue persists only in production. What could be causing this discrepancy between development and production environments, and how can I resolve this issue?

0 Replies