Skip to content

Commit

Permalink
add auth token to ws request
Browse files Browse the repository at this point in the history
  • Loading branch information
aabassiouni committed May 21, 2024
1 parent e841600 commit 2734605
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
16 changes: 14 additions & 2 deletions apps/web/src/components/realtime-switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,36 @@
import { Switch } from "@/components/ui/switch";
import { useWebSocket } from "@/lib/hooks/useWebsocket";
import { useRealtimeCountActions } from "@/lib/store";
import { useAuth } from "@clerk/nextjs";
import { useParams, useRouter } from "next/navigation";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";

export function RealtimeSwitch() {
const router = useRouter();
const params = useParams<{ waitlist: string }>();

const { incrementRealtimeCount, resetRealtimeCount } = useRealtimeCountActions();

const [enabled, setEnabled] = useState(false);
const [token, setToken] = useState<string | null>(null);
const { getToken } = useAuth();

const { ws, reconnect } = useWebSocket(`${process.env.NEXT_PUBLIC_REALTIME_URL}/${params.waitlist}/ws`, {
onMessage: () => {
incrementRealtimeCount();
},
enabled,
authToken: token ?? undefined,
});

useEffect(() => {
async function fetchToken() {
const token = await getToken();
setToken(token);
}

fetchToken();
}, []);

return (
<div className="flex items-center gap-2">
<p className="items-center font-medium text-lg tracking-tight">Enable Realtime</p>
Expand Down
11 changes: 9 additions & 2 deletions apps/web/src/lib/hooks/useWebsocket.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import { useCallback, useEffect, useState } from "react";

export const useWebSocket = (url: string, opts: { onMessage: (e: MessageEvent) => void; enabled: boolean }) => {
export const useWebSocket = (
url: string,
opts: { onMessage: (e: MessageEvent) => void; enabled?: boolean; authToken?: string },
) => {
const [ws, setWs] = useState<WebSocket | null>(null);
const [key, setKey] = useState(0);

const link = new URL(url);

if (opts.authToken) link.searchParams.append("token", opts.authToken);

const reconnect = useCallback(() => {
setKey((prev) => prev + 1);
}, []);

useEffect(() => {
if (opts.enabled) {
const ws = new WebSocket(url);
const ws = new WebSocket(link);
ws.onopen = () => {
console.log("[Connected to realtime]");
};
Expand Down

0 comments on commit 2734605

Please sign in to comment.