Search code examples
amazon-web-servicesnext.jsaws-lambdaaws-amplify-cli

AWS amplify throwing error 500 with api routes in nextjs 12.4


I am working with nextjs 12 where my home page is calling to the route at /api/users/limit-exceed. The api end points work perfectly when i run them locally in both prodction and development. But when I deploy on amplify, the API routes gives error 500 when component send request data using axios. It throw error

XML Parsing Error: syntax error
Location: https://www.caber.com/api/users/limit-exceed
Line Number 1, Column 1:

Here is a code for one of the endpoint I am facing this issue

import supabase from "pages/api/_supabase";
    
   export default async function handler(req, res) {
        
        if (req.method === "GET") {
    
          console.log("body:",req.body)
        try {
    
    
            const data = await supabase.from("users").select('*', { count: 'exact', head: true })
    
             if(process.env.USER_SIGNUP_LIMIT<=data.count){
             
            res.status(200).json({
                data:true,
                users:data.count
            });
            }else{
                res.status(200).json({
                    data:false,
                    users:data.count
                });
            }
    
        } catch (error) {
            console.log("message:",error.message)
            res.status(404).json({ data: "An ERROR OCCUR :"+JSON.stringify(error)  });
    
        } 
    }else {
        // Handle other HTTP methods
        res.status(405).json({ data: "Method not allowed" });
      }
    
    }

But it was perfectly working fine when i run it locally. Every thing on client side working fine except the /api/* where i get above error for all routes

I Found some people also facing this issue or the issue similar in nature in github their was not definite answer i found on github.

https://github.com/aws-amplify/amplify-js/issues/7940

https://github.com/aws-amplify/amplify-hosting/issues/2432

Note: I am using dotenv-vault for setting env variables. For some reason env variable work fine with client but not with server side. here is amplify file

# AWS Amplify build settings.

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm install
        
    build:
      commands:
        - env | grep  -e DOTENV_KEY  >> .env.production
        - npm run build
        - cp -r .next/static .next/standalone/.next/static
        - cp -r public .next/standalone/public
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

Solution

  • After spending much of my time i found out that issue was related to environmental variable. Thus issue is solve by creating script

        // add this in scripts/dotenv.js
    const result = require('dotenv').config({ processEnv: {}, DOTENV_KEY: process.env.DOTENV_KEY})
    const jsonObject=result.parsed
    
    const fs = require('fs');
    
    // Example JSON object
    
    
    // Format key-value pairs
    const envData = Object.entries(jsonObject)
      .map(([key, value]) => `${key}=${value}`)
      .join('\n');
    
    // Write to .env file
    fs.writeFileSync('.env', envData);
    fs.writeFileSync('.env.production', envData);
    

    Now we have to modify amplify.yaml such that it can load environment variables on amplify

    # AWS Amplify build settings.
    
    version: 1
    frontend:
      phases:
        preBuild:
          commands:
            - npm install
            
        build:
          commands:
            - export DOTENV_KEY=${DOTENV_KEY} 
            - node ./scripts/dotenv.js
            - npm run build
            
      
      
      artifacts:
        baseDirectory: .next
        files:
          - '**/*'
      cache:
        paths:
          - node_modules/**/*
    

    Now dotenv will work with server side environmental variables of Nextjs. This code is tested on amplify with dotenv-vault.