Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a parameter into a WebSocket connection with AWS API Gateway?

Following this example project: https://github.com/aws-samples/simple-websockets-chat-app

The onconnect method looks like this:

const AWS = require('aws-sdk');

const ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10', region: process.env.AWS_REGION });

exports.handler = async event => {
  const putParams = {
    TableName: process.env.TABLE_NAME,
    Item: {
      connectionId: event.requestContext.connectionId
    }
  };

  try {
    await ddb.put(putParams).promise();
  } catch (err) {
    return { statusCode: 500, body: 'Failed to connect: ' + JSON.stringify(err) };
  }

  return { statusCode: 200, body: 'Connected.' };
};
  1. How can I see what other fields this event object has? I can't find the documentation.

  2. Can I pass in a parameter from the client when connecting to the websocket? Like wss://path.to.socket/someparameter and how do I access it from this event object?

I want to add another parameter to the database:

const putParams = {
  TableName: process.env.TABLE_NAME,
  Item: {
    connectionId: event.requestContext.connectionId,
    someparameter: event.someparameter               // <-- What's the right way?
  }
};

Thanks!

like image 883
Michael Avatar asked Nov 17 '25 23:11

Michael


1 Answers

To pass parameters when connecting: wss://path.to.socket?param1=value1&param2=value2.

If using wscat you might need to add quotes:

wscat -c 'wss://path.to.socket?param1=value1&param2=value2'

To access to the parameters from the lambda:

exports.handler = async event => {
    const { connectionId, domainName, stage } = event.requestContext;
    const param1 = event.queryStringParameters.param1;
    const param2 = event.queryStringParameters.param2;
    //or: const { param1, param2 } = event.queryStringParameters;

    ...

};
like image 189
LaurentP22 Avatar answered Nov 21 '25 07:11

LaurentP22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!