Search code examples
javascriptamazon-web-serviceswebsocketaws-api-gateway

Send a message to new Websocket connection in AWS API Gateway


I have an AWS API Gateway websocket endpoint for $connect which calls a lambda function. I want that lambda function to send back a message to the user after they connect. Is there any way to do this?

This is what I have tried in the lambda. The message I send is never received, and I assume that is because the connection is not completed yet. However I don't see any way I can send a message after it has been connected.

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

export const handler = async (event) => {
  const domain = event.requestContext.domainName;
  const stage = event.requestContext.stage;
  const connectionId = event.requestContext.connectionId;
  const callbackUrl = `https://${domain}/${stage}`;
  const client = new ApiGatewayManagementApiClient({ endpoint: callbackUrl });

  const requestParams = {
    ConnectionId: connectionId,
    Data: JSON.stringify({ data: "Hello World" }),
  };

  const command = new PostToConnectionCommand(requestParams);

  try {
    await client.send(command);
  } catch (error) {
    console.log(error);
  }

  const response = {
    statusCode: 200
  };
  return response;
};

Solution

  • You cannot do this inside of the handler because the connection is only established once the handler returns without an error.

    Until execution of the integration associated with the $connect route is completed, the upgrade request is pending and the actual connection will not be established. If the $connect request fails (e.g., due to AuthN/AuthZ failure or an integration failure), the connection will not be made.

    source

    You could use another AWS service such as SQS in order to add a message to the queue and have that trigger a lambda which would send the message