Skip to content

Setup example for web sockets in AWS Lambda #4549

@muezz

Description

@muezz

What is the feature you are proposing?

I am working on an API where I need to have a websocket route. Since I need to deploy on AWS Lambda, I am looking to find the right way to set it up.

To run things locally for development, I use the node runtime. I have three main files:

// apps/backend/lambda/app.ts
import { Hono } from "hono/quick";
const app = new Hono<MaybeAuthenticatedApiContext>().basePath("/api");
app.route("/auth", authRoutes);
export default app;
// apps/backend/lambda/index.ts
import { serve } from "@hono/node-server";
serve(
  {
    fetch: app.fetch,
    port: 3000,
  },
  (info) => {
    console.log(`Server is running on http://localhost:${info.port}`);
  }
);
// apps/backend/lambda/handler.ts
import { handle } from "hono/aws-lambda";
import app from "./app";
export const handler = handle(app);

As you can see, app.ts holds the server logic, index.ts allows me to run the server locally and I use handler.ts for deployment on lambda via cdk.

Here is where I am struggling:

// apps/backend/lambda/app.ts
import { Hono } from "hono/quick";
import { createNodeWebSocket } from "@hono/node-ws";
const app = new Hono<MaybeAuthenticatedApiContext>().basePath("/api");
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
app.route("/auth", authRoutes);
app.get(
  "/ws",
  upgradeWebSocket((c) => ({
    // logic for websockets goes here
  }))
);
export default app;

I am struggling here as createNodeWebSocket comes from @hono/node-ws but app.ts needs to be runtime agnostic so it can be used in node for local dev on in AWS Lambda for production. I am also not sure how, where or when to call injectWebSocket.

It would be great if an example could be added in the docs about how to set up websockets in hono in AWS Lambda.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions