ayan_138
ayan_138
KPCKevin Powell - Community
Created by ayan_138 on 5/30/2024 in #back-end
How to synchronize session IDs between Socket.io and API requests using Vite and Express?
I'm working on a project where I need to synchronize session IDs between my Socket.io connections and API requests. I'm using Vite for the frontend and Express with Socket.io for the backend. However, the session IDs for WebSocket connections and API requests are not matching. const sessionConfig = { secret: config.app.Session_Env, resave: true, saveUninitialized: true, store: new FileStore(), cookie: { secure: false, httpOnly: true } }; if (config.app.APP_ENV === "development") { const dir = "./sessions"; const fileStoreOptions = { path: dir, retries: 5, }; if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } sessionConfig["store"] = new FileStore(fileStoreOptions); } const sessionMiddleware = session(sessionConfig); app.use(sessionMiddleware); const io = socketIo(server, { cors: { origin: 'http://localhost:5173', methods: ['GET', 'POST'], credentials: true } }); io.use((socket, next) => { sessionMiddleware(socket.request, socket.request.res || {}, next); }); io.on("connection", OnSocketConnection); //client side import { io } from 'socket.io-client'; const URL = '/socket.io' const socket = io(process.env.API_BASE_URL, { withCredentials: true, }); console.log("Socket: " , socket) export default socket; Despite this setup, the session IDs for my API requests and Socket.io connections are not matching. For example: API Session ID: J8OSLethG4m5pxP1EP1gxj6prWOTSUVi Socket Session ID: vsQ1ZJbaQ0Avp7e4UJL7h7cOWEofPjB6 What am I missing or doing wrong in my configuration? How can I ensure that the session IDs are synchronized across both API and WebSocket connections? Any help or guidance would be greatly appreciated!
1 replies