I’m working on my first website, using Fastify, and my goal today is to securely implement friend invitations using JWT. The issue I’m encountering is that my server needs to notify the client that it has received an invitation. To address this, I’ve found three possible options:
Fetch the server every 5 seconds to check if I’ve received an invitation. I think this is a terrible option.
Another option is to use WebSockets to communicate the invitation, but I can’t send the JWT for authentication (as explained in this post, i can, but it’s mentioned that there is a better solution).
Use server-sent-event. I'm on this method actually, i can send the jwt inside a get request like this :
async function sseConnection(token: string) {
const res = await fetch("http://localhost:3000/user-management/sse", {
method: 'GET',
headers: {
'Content-Type': 'text/event-stream',
'Authorization': `Bearer ${token}`
}
})
const reader = res.body?.pipeThrough(new TextDecoderStream()).getReader() ?? null;
while (reader) {
const {value, done} = await reader.read();
if (done) break;
const parse = sseParse(value);
sseHandler(parse.event, parse.data);
}
}
I found a Fastify plugin for SSE: fastify-sse-v2. Each time I use the .sse method of my response, it triggers reader.read(), and I receive my data.
I need to handle a lot of edge cases, and my code is starting to get messy. I could continue in this direction, but I wanted to ask here if it's necessary to secure this connection with JWT.
If I don't protect it with JWT, I can use EventSource in the browser, and it automatically parses the data. Im open to your suggestions.