惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
I
InfoQ
Engineering at Meta
Engineering at Meta
Jina AI
Jina AI
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
Docker
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
博客园 - Franky
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog RSS Feed
WordPress大学
WordPress大学
MyScale Blog
MyScale Blog
月光博客
月光博客
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Turn WebSockets into Async/Await Requests (AWS WebSocket ...
Rishi · 2026-05-03 · via DEV Community
Cover image for Turn WebSockets into Async/Await Requests (AWS WebSocket API Gateway + Lambda)

Rishi

Some time ago, I was building a chat application using AWS Websocket API gateway. Things were going smoothly. I created a WebSocket API Gateway, added $connect, $disconnect, and sendMessage/addGroup routes. From the frontend (React) side, everything was fire-and-forget. You send a message, and the onMessageHandler takes care of it 💪🏼

But then a new requirement of uploading files using S3 signed URLs came up. That's where I needed the Async/Await promise pattern. Now, one option was to create an HTTP API gateway and use it. But that meant a new connection, a new authorizer, and more setup. At that moment, I wished there was a way to use this existing WebSocket connection to get the signed URL ⭐

wish-movie-refernce

And that’s how this library "ws-await" was born!

It lets you:

  • establish a WebSocket connection
  • send normal fire-and-forget messages
  • send messages and wait for the response using async/await
  • handle reconnection with exponential backoff
  • auto-send heartbeat messages to keep the connection alive

How does it work?

For the async/await pattern, messages from the frontend are sent with a unique requestId. The client keeps a map of pending promises. On the lambda side, the backend reads the requestId and sends it back in the response.

Received messages are analyzed for requestId, and if requestId matches the id of any pending promise in the map, that promise is resolved. If a promise sits idle in the map for a period of more than ~30 seconds, it is rejected.

Steps to use:

Step 1: Install the library in your React project

npm install @tricksumo/ws-await zustand

Step 2: Import createSocket() and establish the connection. Then call ws.send("action") for fire and forget messages and await ws.request("action") for async/await pattern.

import { createSocket } from '@tricksumo/ws-await'
import { useEffect } from 'react'
const ws = createSocket({
  url: 'wss://id.execute-api.us-east-1.amazonaws.com/prod',
})
function App() {
  useEffect(() => {
    ws.connect()
    return () => {
      ws.disconnect()
    }
  }, [])
  const handleGetSignedURL = async () => {
  try {
    const response = await ws.request('getSignedURL', { fileType: 'image/png' })
    console.log('Signed URL:', response)
  } catch (err) {
    console.error('Request failed:', err)
  }
}
  return (
      <div>
        <button onClick={handleGetSignedURL}>
          Click to get signed URL
        </button>
      </div>
  )
}

Enter fullscreen mode Exit fullscreen mode

export default App

Step 3:  Your Lambda must echo the requestId back in its response.

export const handler = async (event) => {

  const { requestId, fileName, fileType } = JSON.parse(event.body || '{}')

  const signedUrl = await getPresignedUrl(fileName, fileType)

  return {
    statusCode: 200,
    body: JSON.stringify({
      signedUrl,
      requestId, // ← REQUIRED: echo it back or the Promise never resolves
    }),
  }

}

Enter fullscreen mode Exit fullscreen mode

Reading the connection state in the frontend.

import { useSocket } from '@tricksumo/ws-await'

function StatusBar() {
  const { isConnected, isConnecting, error } = useSocket()

  if (isConnecting) return <p>Connecting...</p>
  if (!isConnected)  return <p>Disconnected  {error?.message}</p>
  return <p>Connected</p>
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

Initially, this logic was part of my chat application named Chatlings. But I thought it might help others, so I extracted it to create my first ever library 🙌🏼