Search code examples
deploymentnext.jsamazon-cloudfrontaws-amplifyserverless

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

  • 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