Query Parameters
Query parameters are a powerful feature for passing additional data to the server when establishing a socket connection.
With Hyper-fetch, you can set initial query parameters, update the defaults with setQueryParams and resolve them
fresh for every connection attempt with onConnect. This guide will walk you through managing queryParams for your
socket connections.
- How to set initial query parameters when creating a
Socketinstance. - How to update the defaults with the
setQueryParamsmethod and apply them withreconnect. - How to resolve query parameters per connection attempt with the
onConnectinterceptor. - How to ensure type-safety for your query parameters.
Initial Query Parameters
When you create a new Socket instance, you can provide initial query parameters through the queryParams option in
the constructor. These parameters will be appended to the connection URL.
Here's how you can set them up:
const socket = new Socket({
url: "ws://localhost:8080",
queryParams: {
userId: 123,
token: "abc-def",
},
});
Hyper-fetch will automatically infer the types of your queryParams from the initial values, providing you with type
safety from the start.
Dynamic Updates
You can change the queryParams at any time using the setQueryParams method on your Socket instance. It replaces
the defaults used by the next connection attempt. To apply them to a live connection, call reconnect().
This is particularly useful for scenarios where connection details, like dynamic filters, need to change during the application's lifecycle.
Example
Let's see a live example of how dynamic updates work. You can change the userId in the input below and click
"Reconnect" to see the queryParams get updated.
function App() {
const [userId, setUserId] = React.useState("123");
const socket = React.useMemo(() => {
return new Socket({
url: "ws://localhost:8080",
queryParams: {
userId: "123", // initial value
},
});
}, []);
const [queryParams, setQueryParams] = React.useState(socket.queryParams);
const handleReconnect = () => {
socket.setQueryParams({ userId });
socket.reconnect();
setQueryParams(socket.queryParams);
};
return (
<div>
<p>
Current Query Params: <b>{JSON.stringify(queryParams)}</b>
</p>
<input
type="text"
value={userId}
onChange={(e) => setUserId(e.target.value)}
className="mr-2 rounded-md border border-gray-300 px-2 py-1"
/>
<button onClick={handleReconnect} className="rounded-md bg-blue-500 px-4 py-1 text-white">
Reconnect
</button>
</div>
);
}
Resolving Query Params per Connection Attempt
When query params depend on state that changes over time - an access token, the currently selected workspace - keeping
the socket in sync with setQueryParams gets tedious. The onConnect interceptor is called right before every
connection attempt (initial, automatic and manual reconnect) and lets you return the query params to use for that
attempt.
const socket = new Socket({
url: "ws://localhost:8080",
}).onConnect(({ connection }) => ({
...connection,
queryParams: { ...connection.queryParams, token: authStore.getState().accessToken },
}));
The interceptor can be async and receives the reconnection attempt number. See the
authentication guide for a complete walkthrough.
Type-Safety
While Hyper-fetch infers types automatically, you can also enforce stricter type-safety by providing an explicit type
for your queryParams. This is done by passing a generic type to the Socket class.
This practice is highly recommended to prevent runtime errors and ensure that your queryParams always have the correct
shape.
// import { Socket } from '@hyper-fetch/sockets';
interface MyQueryParams {
userId: number;
token: string;
filters?: string[];
}
const socket = new Socket<MyQueryParams>({
url: "ws://localhost:8080",
queryParams: {
userId: 123,
token: "abc-def",
},
});
// This will cause a TypeScript error because `userId` must be a number
socket.setQueryParams({ userId: "not-a-number" });
// This is valid
socket.setQueryParams({ userId: 456, token: "new-token" });
You now know how to effectively manage query parameters with Hyper-fetch sockets.
- You can set initial query parameters in the
Socketconstructor. - You can update the defaults with
setQueryParamsand apply them withreconnect. - You can resolve query parameters per connection attempt with the
onConnectinterceptor. - You can enforce type-safety on your
queryParamsby providing a generic type to theSocketinstance.
