Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot set socket.request to null because the property is read-only #696

Closed
jonathanperret opened this issue Feb 21, 2024 · 2 comments · Fixed by #697
Closed

Cannot set socket.request to null because the property is read-only #696

jonathanperret opened this issue Feb 21, 2024 · 2 comments · Fixed by #697

Comments

@jonathanperret
Copy link
Contributor

jonathanperret commented Feb 21, 2024

Describe the bug

The Socket.IO documentation suggests setting the request property of the socket object received with the connection event to null. But the types as defined do not allow setting that property from a TypeScript program.

To Reproduce

Note that this is a Socket.IO program, because it is taken from the Socket.IO documentation, but it seems clear that the issue comes from the Socket type declared in Engine.IO, which is why I'm opening this issue here.

Socket.IO server version: 4.7.4

Server

import { Server } from "socket.io";

const io = new Server(8080);

io.on("connection", (socket) => {
    console.log(`connect ${socket.id}`);
    socket.request = null;
});

When compiling with tsc server.ts here is the result:

server.ts:7:12 - error TS2540: Cannot assign to 'request' because it is a read-only property.

7     socket.request = null;
             ~~~~~~~

Found 1 error in server.ts:7

Expected behavior

The request property should not be marked read-only, in order to allow this code to compile.

Workaround

Bypassing the restriction works:

(socket as any).request = null;
@sayhicoelho
Copy link

Still can't set it to null on the latest version v4.7.5 using pure Javascript.

Code:

io.on('connection', socket => {
  socket.request = null  
  console.log(socket.request?.session)
})

Output:

Session {
  cookie: {
    path: '/',
    _expires: 2024-08-17T23:50:38.283Z,
    originalMaxAge: 2592000000,
    httpOnly: true,
    domain: '.localhost',
    sameSite: 'lax',
    secure: false
  }
}

@darrachequesne
Copy link
Member

@sayhicoelho this should work:

import { type Socket } from "engine.io";

io.engine.on("connection", (rawSocket: Socket) => {
  rawSocket.request = null;
});

In your example:

io.on('connection', socket => {
  socket.request = null;
})

socket.request is a reference to the underlying request object: https://github.com/socketio/socket.io/blob/1f09a3e97950663cd7c62a34c74af60dad8f0346/packages/socket.io/lib/socket.ts#L991-L996

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants