Next.js on AWS Amplify Throws Server Error Status Code 500

Overview

An application with the next-auth0 SDK works as expected when running on localhost but fails when deployed to AWS Amplify.
Steps to reproduce:

  1. Download Auth0 Next.js quickstart
  2. Deploy to AWS Amplify
  3. Click on Login

When the user clicks on the login button, the browser calls the SDK-provided /api/auth/login endpoint, which responds with status code 500 , internal server error.

Applies To

  • Next.js
  • SDK
  • AWS
  • Amplify

Cause

This can occur when the required environment variables are not available.

Solution

  1. Confirm the environment variables are not available by adding console.log(“AUTH0 SECRET”, process.env.AUTH0_SECRET) to api/auth/[auth0].js:

    // pages/api/auth/[auth0].js
    
    import { handleAuth } from '@auth0/nextjs-auth0';
    
    console.log("AUTH0 SECRET", process.env.AUTH0_SECRET)
    
    export default handleAuth();
    
  2. Inspect the logs on Amplify. If it comes “undefined,” follow additional steps within Amplify settings, as detailed here:

    To make specific environment variables accessible to Next.js, modify the Amplify build specification file to set them in the environment files that Next.js recognizes. This enables Amplify to load these environment variables before it builds the application. The following build specification example demonstrates adding environment variables in the build commands section.

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - env | grep -e DB_HOST -e DB_USER -e DB_PASS >> .env.production
        - env | grep -e NEXT_PUBLIC_ >> .env.production
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
      - .next/cache/**/*