Skip to content

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

Closed

Description

@jonathanperret

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;

Activity

  1. added a commit that references this issue on Feb 21, 2024
    fc22ec6
  2. sayhicoelho commented on Jul 18, 2024

    @sayhicoelho

    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
      }
    }
    
  3. darrachequesne commented on Jul 19, 2024

    @darrachequesne
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions