[experiment] WebSockets with RedwoodJS

Experiments

The Redwood Core team would like to start doing more experiments with things that could go into the framework if there is enough interest and excitement in the community.

Experiments are quick and dirty. Super rough around the edges. Just to play around with what’s possible. Please try them out in a throwaway project or on a throwaway branch in your real project.

WebSocket experiment

The first experiment is WebSockets support for realtime capabilities.

Please let us know if this is something you’d use. And when you’ve tried it, tell us what you loved about the experience and what you hated :smile:

How to try

Quick steps to try the WebSockets experiment

yarn create redwood-app --ts --git rw-ws-experiment
cd rw-ws-experiment
yarn dlx rw-setup-ws
yarn rw g page WebSocket

Replace all content of the newly created page with this:

import { useState } from 'react'

import { useWsContext } from 'src/components/WsContext/WsContext'

const WebSocketPage = () => {
  const [name, setName] = useState('')
  const [message, setMessage] = useState('')
  const ws = useWsContext()

  return (
    <>
      <label>
        Name:{' '}
        <input
          value={name}
          onChange={(event) => {
            setName(event.target.value)
          }}
        />
      </label>
      <br />
      <br />
      <label>
        Message:{' '}
        <input
          value={message}
          onChange={(event) => {
            const message = event.target.value

            // Set the message in component state to make the input
            // value update immediately
            setMessage(message)

            // Send to the server to update all clients (including
            // this one)
            ws.sendMessage(name, message)
          }}
        />
      </label>
      <hr />
      <ul>
        {Object.entries(ws.clients).map(([clientId, clientMessage]) => (
          <li key={clientId}>
            {clientId}: {clientMessage}
          </li>
        ))}
      </ul>
    </>
  )
}

export default WebSocketPage

Run yarn rw dev and go to http://localhost:8910/web-socket in two different browser windows and see the text everyone is typing update in realtime.

Note

This is mostly for localhost experiments for now. It’s not exactly straightforward to deploy this unfortunately. For a production app I recommend Pusher Channels | Build Realtime Real Fast or Realtime | Supabase Docs.

Read more

I got into a little more detail on my blog. (The blog post was written before I wrote the rw-setup-ws command, so it also includes all the steps the setup command now does for you.)

2 Likes