Validating client inputs
PartyKit is flexible, when it comes to data it accepts. You can send arbitrary strings or binary data over WebSockets or in HTTP request bodies to your PartyKit server.
This is handy, but sometimes it may result in receiving unexpected data.
Data schemas
The most ergonomic way to ensure the data you receive is what you expect, is to check it against a schema. There are many great TypeScript libraries for validating input, such as typescript-json-schema, io-ts, yup, and zod.
In this guide, weโll use zod
.
Defining a data schema
zod
allows you to define expected message types using a declarative schema language:
In the above example, the Message
schema can be used to validate all allowed message shapes.
Validating WebSocket messages
Once you specified the schema, you can validate inputs in a type-safe way. In the below example, if the incoming message
does not conform to the Message
schema, the message is ignored:
In addition to runtime validation, zod
uses TypeScript type inference to add an additional layer of type safety to your program, so in the above switch
statement, each type of message is typed based on its schema like below:
Validating HTTP requests
You can use the same schema to validate HTTP request payloads:
Validating responses on the client
Because zod
works in any standard JavaScript environment, we can use the same library on the client side to validate that the server-sent responses are valid.
Define a schema in a shared file, for example in schema.ts
:
You can then validate incoming messages on the client:
If you want to ensure that the server can never accidentally send a response that doesnโt conform to the schema, you can optionally also validate the response data before you send or broadcast it:
Validating binary messages
The above examples assume that the WebSocket messages are JSON strings. However, PartyKit supports sending raw binary data as well.
zod
is agnostic to the data serialization and encoding formats. In all above examples, we have first called JSON.parse
to parse the data to plain JavaScript objects before validating the format.
The same zod
validation approach will work for binary data, as long as you have a way of decoding the raw Uint8Array
into objects:
For more information about binary encodings, read our Handling binary messages guide.