I used Next.js for my frontend.
I separate the token for user login authentication. I generate another token with the secret key provided by Stream.io provider to access the live stream. I'm not sure if my way of implementation was the right thing to do as it is causing an error the way I integrate the generation of token to access the broadcast.
[client]: Failed to connect Error: {"code":4,"StatusCode":400,"message":"WS failed with code: 4 and reason: invalid auth message format","isWSFailure":false} at StableWSConnection.connect (connection.ts:139:17)
I used Stream.io sdk provider for the streaming feature. It's my first time here, I hope I clearly delivered my issue. Thank you so much in advance.
This is my frontend code- stream page
const Stream: React.FC = () => {
const apiKey = "thisIsTheApiKeyy";
const callId = "thiscallid";
const [client, setClient] = useState<StreamVideoClient | null>(null);
const [call, setCall] = useState<any | null>(null);
useEffect(() => {
const initializeStream = async () => {
try {
const userData = await fetchUserData();
console.log("User Data:", userData);
const userId = userData?.user_id;
console.log("User ID:", userId);
if (userId) {
const response = await instance.post('/api/generate-token', { userId });
console.log("STREAM TOKEN response: ", response);
const streamToken = response.data.token;
const streamClient = StreamVideoClient.getOrCreateInstance({
apiKey: apiKey,
user: { id: userId, name: "ML LIVE" },
token: streamToken,
});
setClient(streamClient);
const streamCall = streamClient.call("livestream", callId);
streamCall.join({ create: true });
setCall(streamCall);
} else {
console.error("User ID not found");
}
} catch (error) {
console.error("Error initializing Stream:", error);
}
};
initializeStream();
}, []);
if (!client || !call) {
return <div>Loading...</div>;
}
return (
<StreamVideo client={client}>
<StreamCall call={call}>
<LivestreamView call={call} />
</StreamCall>
</StreamVideo>
);
}
export default Stream;
Below is the backend code using express
backend-generate the stream token
router.post('/generate-token', (req, res) => {
const { userId } = req.body;
if (!userId) {
return res.status(400).json({ error: 'User ID is required' });
}
try {
const token = jwt.sign({ user_id: userId }, process.env.STREAM_API_SECRET, {
algorithm: 'HS256',
});
res.json({ token });
} catch (error) {
console.error('Error generating token:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
This problem has been Fixed, I forgot to include other credentials to generate the stream token. In order to generate the token to access stream you must include or bind the following: apiKey, apiSecret and appId generated from stream dashboard. Previously, I only used the secretKey to generate the token causing an invalid message error. Thank you so much.