Skip to content

NextJS Build fails on Amplify, SSR

0

0

I made a nextjs app, version 14.2.9, typescript, app based routing.

Did npm run build localy and it got built. Able to run locally as well.

When I deployed the app on AWS Amplify, it got built again, ran properly, but after few pushed, the build started failing online. Got different errors, but should not be getting them.

Too long to paste here, so pasting part of it :

                                Error occurred prerendering page "/privacy-policy". Read more: https://nextjs.org/docs/messages/prerender-error
                                    TypeError: Cannot read properties of null (reading 'useContext')
                                    at t.useContext (/codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:109363)
                                    at p (/codebuild/output/src2474594105/src/e-can/.next/server/chunks/46.js:11:221729)
                                    at h (/codebuild/output/src2474594105/src/e-can/.next/server/chunks/46.js:11:213631)
                                    at au (/codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:10446)
                                    at /codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:15122
                                    at aw (/codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:16908)
                                    at a_ (/codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:49776)
                                    at ab (/codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:11808)
                                    at /codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:16871
                                    at aw (/codebuild/output/src2474594105/src/e-can/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:16908)
2024-12-17T20:26:20.237Z [INFO]: ✓ Generating static pages (15/15)
2024-12-17T20:26:20.246Z [WARNING]: 
2024-12-17T20:26:20.246Z [WARNING]: > Export encountered errors on following paths:
                                    /_error: /404
                                    /_error: /500
                                    /_not-found/page: /_not-found
                                    /about-us/page: /about-us
                                    /blogs/page: /blogs
                                    /contact/page: /contact
                                    /delete-account/page: /delete-account
                                    /faq/page: /faq
                                    /maintenance/page: /maintenance
                                    /page: /
                                    /privacy-policy/page: /privacy-policy
                                    /refund-policy/page: /refund-policy
                                    /stores/page: /stores
                                    /terms-and-conditions/page: /terms-and-conditions
2024-12-17T20:26:20.265Z [ERROR]: !!! Build failed
2024-12-17T20:26:20.265Z [INFO]: Please read more about Amplify Hosting's support for SSR frameworks to find if your build failure is related to an unsupported feature: https://docs.aws.amazon.com/amplify/latest/userguide/amplify-ssr-framework-support.html. You may also find this troubleshooting guide useful: https://docs.aws.amazon.com/amplify/latest/userguide/troubleshooting-ssr-deployment.html
2024-12-17T20:26:20.265Z [ERROR]: !!! Error: Command failed with exit code 1
2024-12-17T20:26:20.265Z [INFO]: # Starting environment caching...
2024-12-17T20:26:20.265Z [INFO]: # Environment caching completed

What is weird that I am still able to build properly locally + even on new amplify app.

I tried commenting the cache part in build settings, but the build still fails!

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci --cache .npm --prefer-offline
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
#  cache:
#    paths:
#     - .next/cache/**/*
#      - .npm/**/*
asked a year ago1.8K views
2 Answers
0

If you are here from the past or in future,,this error is a monster,I know you have googled and your Chatgpt and AI tools were not able to fix .It troubled me for 12hrs straight😭 but I finally fixed it ,

This is the solution ,,

Understand the error

Getting a 500 Internal Server Error when deploying my Next.js 13 and above application to AWS Amplify, even though it builds and runs perfectly locally. The error occurs during runtime, not during the build process.

The Root cause

Builds on Amazon Amplify do not include the envs during the build process like vercel and Netlify.

Amplify Console environment variables are not automatically available during the build process

  • Next.js requires environment variables to be present in .env.production for server-side code

  • Missing environment variables cause authentication and database connection failures

  • Next.js 15 has specific requirements for React bundling in serverless environments

  • AWS Lambda runtime requires the __NEXT_PRIVATE_PREBUNDLED_REACT=next flag

  • UI libraries (Radix UI, Lucide React, etc.) need proper transpilation for server environments

  • ES modules not properly handled in AWS Lambda runtime

Solution 👌

1.Configure Next.js for Amplify Compatibility in your next.config.mjs


/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
  typescript: {
    ignoreBuildErrors: true,
  },
  images: {
    unoptimized: true,
  },
  
  // Critical for Amplify deployment
  output: 'standalone',
  
  // Transpile packages that cause issues in Amplify deployment
  transpilePackages: [
    // Radix UI packages
    '@radix-ui/react-accordion',
    '@radix-ui/react-alert-dialog',
    '@radix-ui/react-avatar',
    '@radix-ui/react-checkbox',
    '@radix-ui/react-dialog',
    '@radix-ui/react-dropdown-menu',
    '@radix-ui/react-label',
    '@radix-ui/react-popover',
    '@radix-ui/react-select',
    '@radix-ui/react-tabs',
    // Add other UI libraries you're using
    'lucide-react',
    'cmdk',
    'class-variance-authority',
    'framer-motion',
    'recharts',
    // Add any RC packages
    'rc-pagination',
    'rc-util',
    // Add other problematic packages
  ],
  
  // Server external packages
  serverExternalPackages: ['postgres', 'pg', '@aws-sdk/client-s3'],
  
  // Webpack configuration
  webpack: (config, { isServer }) => {
    // Handle ES modules properly
    config.resolve.extensionAlias = {
      '.js': ['.ts', '.tsx', '.js', '.jsx'],
      '.mjs': ['.mts', '.mjs'],
    };
    
    // Client-side fallbacks for Node.js modules
    if (!isServer) {
      config.resolve.fallback = {
        ...config.resolve.fallback,
        fs: false,
        net: false,
        tls: false,
      };
    }
    
    return config;
  },
  
  poweredByHeader: false,
}

export default nextConfig

2.Create Proper amplify.yml Configuration (This is the life saver🤞)


version: 1
your app name:
  phases:
    preBuild:
      commands:
        - npm install --legacy-peer-deps
    build:
      commands:
        # Critical Next.js fix for Amplify
        - echo "__NEXT_PRIVATE_PREBUNDLED_REACT=next" >> .env.production
        
        # Inject environment variables from Amplify Console
        - echo "NEXTAUTH_URL=$NEXTAUTH_URL" >> .env.production
        - echo "NEXTAUTH_SECRET=$NEXTAUTH_SECRET" >> .env.production
        - echo "GOOGLE_CLIENT_ID=$GOOGLE_CLIENT_ID" >> .env.production
        .env.production
        
        # Add any other environment variables you need here 
        - echo "NEXT_AWS_S3_ACCESS_KEY_ID=$NEXT_AWS_S3_ACCESS_KEY_ID" >> .env.production
        - echo "NEXT_AWS_S3_SECRET_ACCESS_KEY=$NEXT_AWS_S3_SECRET_ACCESS_KEY" >> .env.production
        
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - .next/cache/**/*
      - node_modules/**/*

Then redeploy your app and see it work as you sip your cofee.

I sufferd 12hrs for you to be saved 😒,welcome in advance (I know you will thank me)

answered 4 months ago
-1

The issue you're experiencing with your Next.js app failing to build on AWS Amplify, despite building successfully locally, could be due to a few factors:

  1. Server-Side Rendering (SSR) Support: AWS Amplify Hosting has recently introduced support for SSR applications, including Next.js. However, there might be some compatibility issues with certain Next.js features or configurations.

  2. Build Image: Amplify Hosting has updated its default build image to Amazon Linux 2023, which includes newer versions of Node.js (18 and 20). This change might affect your build process if your local environment uses a different Node.js version.

  3. Environment Variables: There could be missing or incorrect environment variables in your Amplify build settings that are present in your local environment.

  4. Dependencies: There might be a mismatch between the dependencies installed locally and those installed during the Amplify build process.

To troubleshoot this issue:

  1. Ensure you're using the latest version of Amplify Hosting's build image (Amazon Linux 2023).

  2. Check that all necessary environment variables are correctly set in your Amplify console.

  3. Review your dependencies, especially those related to React and Next.js, to ensure they're compatible with the version of Next.js you're using.

  4. Consider using the Amplify CLI to deploy your Next.js application, as it might provide a more streamlined process for SSR apps.

  5. If the issue persists, you may need to investigate the specific error related to "useContext" in your application code, as it suggests a problem with React's context API usage.

  6. Review the Amplify documentation for SSR framework support and troubleshooting guides for additional insights.

If these steps don't resolve the issue, you might need to create a new Amplify app and redeploy your project, as you mentioned it works on a new Amplify app. This could help isolate whether the problem is with your project configuration or the Amplify environment itself.
Sources
Introducing Support for Hosting Any SSR app on AWS Amplify Hosting | Front-End Web & Mobile
Deploy Next.js 14 SSR apps with AWS Amplify Hosting’s Amazon Linux 2023 Support | Front-End Web & Mobile
AWS Amplify JavaScript’s NEW developer preview with reduced bundle size, improved TypeScript and Next.js support | Front-End Web & Mobile

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.