Here are steps to follow: Step One: Create WebSocket API
In this step, we create a WebSocket API using AWS API Gateway. The API is designed to facilitate real-time communication and supports WebSocket connections.

const webSocketApi = new apigwv2.CfnApi(this, "MyWebSocketAPI", {
  protocolType: "WEBSOCKET",
  routeSelectionExpression: "$request.body.action",
  name: 'mywsapi',

Step Two: Create Integration, Routes, Deployment, and Stage
Next, we configure the WebSocket API by creating integrations, defining routes, and setting up deployment and stage for the API. This ensures proper routing and handling of WebSocket requests.

const apiGatewayDeployment = new apigwv2.CfnDeployment(this, "APIGatewayDeployment", {
  apiId: webSocketApi.ref,

const apiGatewayStage = new apigwv2.CfnStage(this, "APIGatewayStage", {
  apiId: webSocketApi.ref,
  autoDeploy: true,
  deploymentId: apiGatewayDeployment.ref,
  stageName: "v1",
  defaultRouteSettings: {
    throttlingBurstLimit: 500,
    throttlingRateLimit: 1000,

Step Three: Request a Certificate using AWS Certificate Manager (ACM)
For secure communication over WebSocket, we obtain a custom SSL/TLS certificate using AWS Certificate Manager (ACM). This certificate will be used to encrypt WebSocket connections.
const webSocketCertificate = new certManager.Certificate(this, "WebSocketCertificate", {
  domainName: `*.${DOMAIN_NAME}`,
  subjectAlternativeNames: [DOMAIN_NAME],
  validation: certManager.CertificateValidation.fromDns(hostedZone),

Step Four: Map Custom Domain to the Issued Certificate
To access the WebSocket API using a custom domain, we map the WebSocket API to a custom domain name associated with the issued SSL/TLS certificate.

const webSocketDomainName = new DomainName(this, "WebSocketDomainName", {
  domainName: `ws.` + DOMAIN_NAME,
  certificate: webSocketCertificate,

Step Five: Associate WebSocket API with Custom Domain and Stage
Finally, we associate the WebSocket API with the custom domain and the previously created deployment stage to enable secure WebSocket communication.

new apigwv2.CfnApiMapping(this, "WebSocketDomainMapping", {
  apiId: webSocketApi.ref,
  domainName: webSocketDomainName.domainName,
  stage: apiGatewayStage.ref,

With this, we can create a WebSocket API with a custom domain name and a secure SSL/TLS certificate using AWS API Gateway. This setupensures reliable and encrypted real-time communication for your applications, enhancing security and privacy.