You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We currently use partysocket and need to add an Authentication header with a bearer token, but the only way to do this is with the "Websocket Constructor" trick:
import { WebSocket } from "partysocket";
import type { ClientRequestArgs } from "node:http";
import { type ClientOptions, WebSocket as wsWebSocket } from "ws";
new WebSocket(websocketUrl.href, [], {
WebSocket: WebsocketFactory(accessToken),
});
function WebsocketFactory(apiKey: string) {
return class extends wsWebSocket {
constructor(address: string | URL, options?: ClientOptions | ClientRequestArgs) {
super(address, { ...(options ?? {}), headers: { Authorization: `Bearer ${apiKey}` } });
}
};
}
Is it possible using the params option to add headers? If not, it would be great to add this functionality 👍
The text was updated successfully, but these errors were encountered:
thankx @ericallam for opening the first issue on Socket :)
socket was primarily made with browsers in mind. so it very much also works similarly to partysocket in this case. as the header option is not something available on the client side (browsers).
i am thinking for a little more general purpose solution for this case. what do you think of this solution below?
params: async(info)=>{constprotocols: string[]=[];constextraOptions={headers: {Authorization: "Bearer token",},};return{//this gets added to the queryquery: {},//these are passed to the websocket constructor -> new Websocket(url, ...extraOptions)extraOptions: [protocols,extraOptions],};},
or maybe something like this
newSocket(url,protocols,{extraOptions: [options]// these are passed to the websocket constructor -> new Websocket(url, protocols, ...extraOptions)})
or a new option altogether that makes sense for nodejs/server-side clients. the difference between this and the extraOptions above is. the one above is pretty much static. but this one is a function that also receives the data you return from params function and is more flexible~
newSocket(url,protocols,{//authData is the data you return from params. extraOptions: (authData: any)=>{return[options]//these are passed to the websocket constructor -> new Websocket(url, protocols, ...extraOptions)}})
I personally prefer the last extraOptions . as it is more flexible and dynamic. let me know what you think!
We currently use
partysocket
and need to add an Authentication header with a bearer token, but the only way to do this is with the "Websocket Constructor" trick:Is it possible using the
params
option to add headers? If not, it would be great to add this functionality 👍The text was updated successfully, but these errors were encountered: