Usage
Validation
Validation utils for incoming messages from the client.
Two validation utilities are available server-side to validate incoming messages from the client. They are based on Standard Schema, allowing you to use your preferred validation library.
wsValidateMessage
wsSafeValidateMessage
wsValidateMessage
Validates a WebSocket message against a given schema. If the message is invalid, the function throws an error with the validation issues. Otherwise, it returns the validated message. If the message is a Message object, it's parsed with wsParseMessage
before validation.
import * as v from 'valibot'
message(peer, message) {
const parsedMessage = await wsValidateMessage(
v.object({
type: v.picklist(['subscribe', 'unsubscribe']),
topic: v.picklist(['chat', 'notifications']),
}),
message,
)
// or directly the incoming message type
const blob = await wsValidateMessage(v.blob(), message.blob())
const helloWorld = await wsValidateMessage(v.literal('Hellow World'), message.text())
}
import { z } from 'zod'
message(peer, message) {
const parsedMessage = await wsValidateMessage(
z.object({
type: z.enum(['subscribe', 'unsubscribe']),
topic: z.enum(['chat', 'notifications']),
}),
message,
)
// or directly the incoming message type
const blob = await wsValidateMessage(z.blob(), message.blob())
const helloWorld = await wsValidateMessage(z.literal('Hellow World'), message.text())
}
wsSafeValidateMessage
Same as wsValidateMessage
, but instead of throwing an error, it returns an object with the validation issues if the message is invalid. Otherwise, it returns the validated message.
import * as v from 'valibot'
message(peer, message) {
const parsedMessage = await wsSafeValidateMessage(
v.object({
type: v.picklist(['subscribe', 'unsubscribe']),
topic: v.picklist(['chat', 'notifications']),
}),
message,
)
if (parsedMessage.issues) {
console.error('WebSocket:', peer.id, parsedMessage.issues)
peer.send(JSON.stringify({
topic: '_internal', // Assuming being used
message: `Invalid message: ${parsedMessage.issues}`
}))
}
// else do something with parsedMessage.value
}
import { z } from 'zod'
message(peer, message) {
const parsedMessage = await wsSafeValidateMessage(
z.object({
type: z.enum(['subscribe', 'unsubscribe']),
topic: z.enum(['chat', 'notifications']),
}),
message,
)
if (parsedMessage.issues) {
console.error('WebSocket:', peer.id, parsedMessage.issues)
peer.send(JSON.stringify({
topic: '_internal', // Assuming being used
message: `Invalid message: ${parsedMessage.issues}`
}))
}
// else do something with parsedMessage.value
}