Responding to HTTP requests
In addition to serving real-time WebSocket traffic, PartyKit servers can respond to regular HTTP requests.
Let’s send a request to the room’s public URL:
The PartyKit hosting environment uses the https
protocol by default, but in local development you are most likely using http
, so in practice, your code might look something like this:
To make this easier, the partysocket
package exports a PartySocket.fetch
utility that constructs the correct URL for you:
Handle incoming requests
To handle incoming requests, define an onRequest
handler in your PartyKit server:
In the above example, the client can send messages via an HTTP POST
request, and fetch all messages with a GET
request.
Push/pull
The above code snippet implements a simple stateful HTTP server, but did you notice the following line hidden in the POST
handler?
The onRequest
method has access to all of the room’s resources, including connected WebSocket clients.
As simple as this sounds, this is a powerful pattern. Being able to access the same party state with both WebSockets and HTTP requests enables us to create flexible push/pull systems that integrate well with third-party systems such as:
- fetching initial page data for, for example, React server rendering,
- interacting with the room from environments that don’t support WebSockets,
- using parties as webhook endpoints for third-party services,
- messaging between multiple parties,
- building room admin APIs.
To learn more common patterns and uses cases, head over to the Examples section.