Rahul
Rahul

Reputation: 379

How to send custom headers from JavaScript WebSocket client to the server?

I know there are no standard JS WebSocket APIs for the same. My main aim is to send the info like resourceId, routingInfo, auth-token, protocol etc. from JS web-socketclient to the server.

I could think of below few approaches. Kindly share the thoughts if my approach is fine or is there any other better approach:

  1. Can we use cookies for sending the custom headers from client and retrieve them in server side?

  2. Can we use web-storage API for storing them in the browser and retrieve them on server side?

PS: I am using a Java based server

Upvotes: 4

Views: 6187

Answers (1)

jfriend00
jfriend00

Reputation: 707318

Assuming you're talking about a webSocket connection from a browser, here are your traditional choices for sending additional "header-like" information.

  1. You can encode them as a query parameters on the initial URL which might be fine for everything except auth-token.
  2. If the origin you are connecting the webSocket connection is the same as the origin of your web page, then you can put the parameters into cookies and those cookies will be sent with the original webSocket connection request where the server can retrieve them upon the connection request.
  3. You can make a "conditional" webSocket connection to the server and then send credentials in subsequent webSocket messages. You'd have to implement safety for that on your server so that the "conditionally" connected webSocket was not allowed to do anything else except authenticate itself and probably timeout the connection if appropriate credentials do not arrive shortly.

As it sounds like you may already know, the browser interface to webSockets does not allow custom headers on the initial HTTP request that starts the webSocket connection. Those custom headers are possible from some other kind of client - it's just that the browser interface to a webSocket connection does not have that feature.

Can we use web-storage API for storing them in the browser and retrieve them?

The Javascript in your web page can use the web-storage API to store data in the browser and that data can be retrieved later from another script in a page from the same origin. That data is not available to the server, it is only available within the client.

Upvotes: 5

Related Questions