'After successfully deploying Next.js app on AWS Amplify, https://www.example.com/api/any-route showing below error in console

The app is deployed successfully but the API routes (/pages/api) are not working as expected, showing below error in the console.

Build is successful and deployed on aws-amplify, I have added environment variables correctly, don't know why this is happening?

Does aws-amplify doesn't support serverless functions writer inside /api folder??

{
"error": {
"message": "connect ECONNREFUSED 127.0.0.1:80",
"name": "Error",
"stack": "Error: connect ECONNREFUSED 127.0.0.1:80\n    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16)",
"config": {
"url": "undefined/campaigns",
"method": "get",
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/0.21.4"
},
"auth": {},
"transformRequest": [null],
"transformResponse": [null],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
}
},
"code": "ECONNREFUSED"
}
}

Here is the code

import axios from 'axios';
import Cors from 'cors';
import rateLimit from '../../../utils/rate-limit';
import initMiddleware from '../../../lib/init-middleware';

// Initialize the cors middleware
const cors = initMiddleware(
  Cors({
    methods: ['POST'],
    origin: ['https://www.example.com', /\.example\.com$/],
  })
);

const limiter = rateLimit({
  interval: 60 * 1000, // 60 seconds
  uniqueTokenPerInterval: 500, // Max 500 users per second
});

const handler = async (req, res) => {
  await cors(req, res);

  if (req.method === 'GET') {
    try {
      await limiter.check(res, 50, 'CACHE_TOKEN');

      const { data } = await axios.get(`${process.env.BASE_URL}/campaigns`, {
        auth: {
          username: process.env.MAIL_SERVER_USERNAME,
          password: process.env.MAIL_SERVER_PASSWORD,
        },
      });
      return res.status(200).json(data);
    } catch (error) {
      return res.status(429).json({ error });
    }
  } else {
    try {
      await limiter.check(res, 10, 'CACHE_TOKEN'); // 10 requests per minute
      return res.status(200).json('not allowed');
    } catch (err) {
      return res.status(429).json({ error: 'Rate limit exceeded' });
    }
  }
};

export default handler;



Solution 1:[1]

I figured out that environment variables are not getting reflected, so did some googling; found this solution and it worked for me. Add your desired environment variable in the Amplify Console-like normal (steps) Update (or create) your next.config.js file with the environment variable you added in the Amplify Console. E.g if you created an environment variable named MY_ENV_VAR in the console in step 1) above, then you would add the following:

module.exports = {
  env: {
    MY_ENV_VAR: process.env.MY_ENV_VAR
  }
};

Now after your next build you will be able to reference your environment variable (process.env.MY_ENV_VAR) in your SSR lambdas!

Here is the link: Github

Solution 2:[2]

Ran into the same problem Amplify only supports NextJS 11 at the moment. If you go with the default settings it will use the latest NextJS 12 and /api routes wont work, they return a 503 with a cloudformation permission error.

Specify next 11.1.3 in your package.json

https://aws.amazon.com/about-aws/whats-new/2021/08/aws-amplify-hosting-support-next-js-version-11/

Solution 3:[3]

I also faced that problem. Amplify does not support v12 of next. Simply downgrade your next.js version in package.json to v1.1.3 and your routes will work as normal.

Best regrets. Artem Meshkov

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pranjal Soni
Solution 2 Steven Hall
Solution 3 ArtemNikov