Skip to content

Full declaration syntax is not typed correctly for websocket: true #314

Open
@yakovenkodenis

Description

@yakovenkodenis

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.2.0

Plugin version

11.0.1

Node.js version

22.12

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

Sonoma 14.5

Description

It seems that the full declaration syntax is not supported by @fastify/websocket types.

Also, when the wsHandler property is set, the behaviour is the following:

  • the handler property is still required and typescript throws error when it is not in place;
  • when the handler property is also set, the ws connection is handled by the handler property while wsHandler is ignored.

Is this the expected behaviour?

import Fastify from 'fastify';
import FastifyWebsocket from '@fastify/websocket';

const app = Fastify();
app.register(FastifyWebsocket);

app.route({
  method: 'GET',
  url: '/',
  websocket: true,
  handler: async (websocket, request) => {
    // 'websocket' is typed as FastifyRequest, not WebSocket
    // 'request' is typed as FastifyReply, not FastifyRequest
  },
});

app.route({
  method: 'GET',
  url: '/',
  websocket: true,
  wsHandler: (socket, request) => {
    console.log('WS'); // not printed
  },
  handler: (socket, request) => {
    console.log(socket.constructor.name === 'WebSocket'); // prints true (when executing "new WebSocket('ws://localhost:3000/')" in the browser)
  },
});

Somewhat related issue: #133

Expected Behavior

  1. The full declaration syntax (RouteOptions type) is typed correctly.
  2. wsHandler is executed for ws connection when both handler and wsHandler are defined.

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