Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websocket connection to AppSync: ErrorCode 400 'NoProtocolError'

I'm trying to make a direct websocket connection to appsync, but right after connecting I get keep getting an NoProtocolError error ( {"payload":{"errors":[{"message":"NoProtocolError","errorCode":400}]},"type":"connection_error"}')

This is my code

let ws = undefined;

const startWebsocket = () => {
    const url = 'wss://XXXX.appsync-realtime-api.YYYY.amazonaws.com/graphql';
    ws = new WebSocket(url);

    // just log everything
    ws.onopen    = (e) => {console.log('Socket opened',   e);};
    ws.onmessage = (e) => {console.log('Msg    received', e);};
    ws.onclose   = (e) => {console.log('Socket closed',   e);};
    ws.onerror   = (e) => {console.log('Socket error',    e);};
};
like image 870
DarkTrick Avatar asked Jun 16 '26 18:06

DarkTrick


1 Answers

Regarding the immediate question

The message is referring to the second parameter of the Websocket constructor: protocols. (MDN reference here)

You need to specify the protocol (more precise subprotocol) like below:

ws = new WebSocket(url, ['graphql-ws']);

However

Be aware, that you're also missing header information, payload information and the whole handshake.

Only changing adding the protocol will present you with the next error: Both, the "header", and the "payload" query string parameters are missing.

Further Information

Read more about how to build up a connection on aws.amazon.com.

Open websocket with header and payload

const api_header = {
  host: 'XXXX.appsync-api.YYYY.amazonaws.com',
  'x-api-key': '<YOUR APPSYNC API KEY>',
};

// payload should be an empty JSON object
const payload = {};

const base64_api_header = btoa(JSON.stringify(api_header));
const base64_payload = btoa(JSON.stringify(payload));

const appsync_url = url + '?header=' + base64_api_header + '&payload=' + base64_payload;

ws = new WebSocket(appsync_url, ['graphql-ws']);

Note that the host is appsync-api and not appsync-realtime-api

With this, you should see a 'ka' message and can go forward with the handshake (see next section).

How to do the handshake

See this document on AWS enter image description here

References

  • WebSocket API referene (mentioning of second parameter)
  • PHP implementation for WebSocket to AppSync
  • Amazon's doc on how to connect to AppSync
like image 127
DarkTrick Avatar answered Jun 18 '26 06:06

DarkTrick



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!