Home > Back-end >  How can I change websocket connection IDs in AWS API Gateway?
How can I change websocket connection IDs in AWS API Gateway?

Time:10-14

I am curious how does AWS Websocket ApiGateway generate connectionIDs and if it is possible to customize how they are generated?

$context.connectionId = A unique ID for the connection that can be used to make a callback to the client.

For example, I would like the connection ID to always have the same value (the user ID in my DB) whenever he is connected.

If user ID = 1 then connection ID should also = 1 and it is the client app responsibility to enforce uniqueness.

CodePudding user response:

No, it is not possible to modify the auto-generated connection ID.


When a WebSocket client requests a new connection, API Gateway assigns an auto-generated connection ID e.g. AjKdsJDkDJfgmDJ= to that session and invokes your $connect Lambda function with the ID in the event payload (event.requestContext.connectionId).

You can't answer How is the connection ID generated? as it's not a GUID nor a number but it's definitely a random value generated by something.

You can use this connection ID to send a message directly back to the client in the same function invocation.

If you want to also be able to send a message later on, store the connection ID in a data store - DynamoDB for example - along with a mapping to your user IDs.

This way, you can look up your table by the user ID & then obtain the connection ID for interacting with them and vice-versa.

  • Related