WebsocketApi Lambda and connect ECONNREFUSED

0

Hello, I've been setting up Websocket API with Lambda and I received following error:

<message-id>	INFO	Error: connect ECONNREFUSED <ip>
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: <ip>,
  port: 80,
  '$metadata': { attempts: 1, totalRetryDelay: 0 }

Env is a Node18 and Postman (ws) as a client.

Lambda's code:

import { ApiGatewayManagementApiClient, DeleteConnectionCommand,PostToConnectionCommand } from "@aws-sdk/client-apigatewaymanagementapi";

const api = new ApiGatewayManagementApiClient({endpoint: 'wss://<id>.execute-api.<region>.amazonaws.com/production',
    region: 'eu-central-1'
})


export const handler = async (event) => {
    
    
    console.log(event);
    
    const {routeKey, connectionId} = event?.requestContext
    let msg;
    
    console.log(`Request key is ${routeKey} and connectionID is ${connectionId}`)
    
    switch(routeKey){
        case '$connect':
            msg = 'connected My friend';
            break;
            
        case '$disconnect':
            msg = 'disconnected my friend';
            break;
            
        case 'message':
            try{
                await replyToMessage(connectionId, 'RAMP PAM PAM')
            }catch(e){
                console.log('EXEPTION ALARM')
                console.log(e)
            }
            break;
            
        default:
            console.log('something bad happened', routeKey);
            break;
    }
    
    // TODO implement
    const response = {
        statusCode: 200
    };
    
    
    return response;
};

const replyToMessage = (ConnectionId, message) =>{
        const data = {message};
        const cmd = new PostToConnectionCommand({
            ConnectionId,
            Data: Buffer.from(JSON.stringify(data))
        })
        
        const result =  api.send(cmd);
        console.log(result)
        return result;
    }

Lambda's policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "execute-api:*",
            "Resource": "arn:aws:execute-api:<region><id>:<api-id>/production/*"
        }
    ]
}

Thank you in advance, Arczik!

2 Answers
1

The endpoint used in replyToMessage in provided code snippet has 'wss' prefix, which means it is a websocket endpoint. To send a message to a connected client using 'ConnectionId' of the client, 'connections' endpoint needs to be used which has 'https' protocol. Updating the endpoint protocol 'wss' as in the following snippet to 'https' may help.

const api = new ApiGatewayManagementApiClient({endpoint: 'wss://<id>.execute-api.<region>.amazonaws.com/production',
    region: 'eu-central-1'
})

Reference: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.htmlvice

AWS
SUPPORT ENGINEER
Udit_P
answered 10 months ago
0

I think you getting this error on the client side. Is it correct? The error indicates that you are trying to connect over port 80. API Gateway only supports port 443 using wss: protocol. I am guessing this is the reason for the error.

profile pictureAWS
EXPERT
Uri
answered a year ago
  • @Uri thank you for your answer. In Postman I have a 'wss:/'/ prefix before api url. I get above mentioned error in 'replyToMessage' when I try to send message back to client.

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.

Guidelines for Answering Questions