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

Per-route context Variables with upgradeWebSocket #3845

Open
moroshko opened this issue Jan 21, 2025 · 1 comment
Open

Per-route context Variables with upgradeWebSocket #3845

moroshko opened this issue Jan 21, 2025 · 1 comment
Labels
enhancement New feature or request.

Comments

@moroshko
Copy link

What is the feature you are proposing?

Currently, context variables can be defined in normal (non-WebSocket) routes like this:

type ContextVariables = {
  foo: number;
}

const app = new Hono<{ Variables: ContextVariables }>();

app.get('/', (c) => {
  const foo = c.var.foo; // number
  ...
})

But, when using upgradeWebSocket from hono/bun, the types don't work:

import { createBunWebSocket } from 'hono/bun'
import type { ServerWebSocket } from 'bun'

const { upgradeWebSocket, websocket } = createBunWebSocket<ServerWebSocket>()

type ContextVariables = {
  foo: number;
}

const app = new Hono<{ Variables: ContextVariables }>()

app.get(
  '/ws',
  upgradeWebSocket((c) => {
    const foo = c.var.foo; // any
    ...
  })
)

Globally extending ContextVariableMap is problematic when the app has multiple routes where every route has its own context fields:

declare module 'hono' {
  interface ContextVariableMap {
    foo: number;
  }
}

It would be nice to have the ability to specify context variables per WebSocket route, e.g.:

app.get(
  '/ws1',
  upgradeWebSocket<{ Variables: { foo: number, bar: boolean } }>((c) => {
    const foo = c.var.foo; // number
    const bar = c.var.bar; // boolean
    ...
  })
)


app.get(
  '/ws2',
  upgradeWebSocket<{ Variables: { foo: string } }>((c) => {
    const foo = c.var.foo; // string
    const bar = c.var.bar; // Property 'bar' does not exist...
    ...
  })
)
@moroshko moroshko added the enhancement New feature or request. label Jan 21, 2025
@yusukebe
Copy link
Member

Thanks!

This is related to #3202

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request.
Projects
None yet
Development

No branches or pull requests

2 participants