Skip to content

docs: WebSocket docs improvements #5883

Open

Description

@kzuraniewski

Area of Improvement

When following the WebSocket configuration guide, I found it lacking of some information that I think would be a good addition:

  • How to setup WebSocket client along the standard HTTP client
  • How to setup WebSocket server for a nested router

Another thing is, when defining a WebSocket handler for an already existing router in Express.js, I could not reuse the following createContext function as the types mismatch:

const createContext = ({ req, res }: CreateExpressContextOptions) => {
    const jwt = validateToken(req.cookies['token']);

    return {
        jwt,
    };
};

In some examples I've noticed the type CreateExpressContextOptions | CreateWSSContextFnOptions being applied on the argument. The problem is, I am accessing res.cookies property that is omitted in the union. What confuses me is whether this is a TypeScript problem or an implementation problem. Should I type the createContext properly? Should I adjust it to handle both the Express middleware and the WebSocket handler? Or should I create a separate one for both? Some coverage on this topic would also be welcome.

Link to related docs

https://trpc.io/docs/websockets

Additional information

No response

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR implementing the suggested changes!

Activity

  1. added
    📚 documentation / examples
    on Jul 9, 2024
  2. BeBoRE commented on Jul 9, 2024

    @BeBoRE
    Contributor

    I've opted to use 2 seperate createContext functions since the logic is so different to retrieve the correct data.

    You have to substract the cookies yourself from the headers when using WebSockets since Express handles that for you in the ExpressHandler.

  3. added
    ✅ accepted-PRs-welcome
    on Sep 23, 2024
  4. YKDZ commented on Dec 2, 2024

    @YKDZ

    I opted to define 2 of createContext functions and used them to init trpc server:

    // trpc/http/context.ts
    import { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch'
    import { RoleSchema } from '@/schemas/prisma'
    import { userFromSession } from '@/server/utils/session'
    import prisma from '@/server/database/prisma'
    
    export const createHttpContext = async ({
      req,
      resHeaders,
    }: FetchCreateContextFnOptions) => {
      const sessionId = req.headers.get('Cookie')?.match(/sessionId=([^;]+)/)?.[1]
    
      const user = await userFromSession(sessionId)
    
      return {
        sessionId,
        user,
      }
    }
    
    export type HttpContext = Awaited<ReturnType<typeof createHttpContext>>
    // trpc/ws/context.ts
    import { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws'
    
    export const createWSContext = async ({
      req,
      res,
      info,
    }: CreateWSSContextFnOptions) => {
      const token = info.connectionParams?.token
    
      // [... authenticate]
    
      return {
        token
      }
    }
    
    export type WSContext = Awaited<ReturnType<typeof createWSContext>>

    Then follow the documentation:

    // Init ws server
    const wss = new WebSocketServer({
      port: port + 1,
    })
    
    const handler = applyWSSHandler({
      wss,
      router: appRouter,
      createContext: createWSContext,
      keepAlive: {
        enabled: true,
        pingMs: 30000,
        pongWaitMs: 5000,
      },
    })
    
    // Init http server use hono.js
    const app = new Hono()
    
    app.all('*', (c) => {
      return fetchRequestHandler({
        endpoint: '/api/trpc',
        req: c.req.raw,
        router: appRouter,
        createContext: createHttpContext,
      })
    })
    
    export const trpcHandler = app

    For the router type issue, I take the following approach:

    const t = initTRPC.context<HttpContext | WSContext>().create()
    
    export const { router, createCallerFactory } = t
    
    export const publicHttpProcedure = t.procedure.use((opts) => {
      return opts.next({
        ctx: opts.ctx as HttpContext,
      })
    })
    
    export const publicWSProcedure = t.procedure.use((opts) => {
      return opts.next({
        ctx: opts.ctx as WSContext,
      })
    })

    I'm not an expert on trpc, but the above at least works properly for me.

  5. dewa3355 commented on Sep 2, 2026

    @dewa3355

    I'll take this: expand the WebSocket docs with HTTP+WS together, nested routers, and the two-createContext pattern (CreateExpressContextOptions vs CreateWSSContextFnOptions, cookies from headers).

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

    ✅ accepted-PRs-welcome📚 documentation / examples

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions