Using plugins

Add support for more types with plugins, and use the web plugins from seroval-plugins.

Plugins add support for types that seroval does not handle itself. To use one:

  1. Install the package that has the plugin, such as seroval-plugins.
  2. Pass the plugin in the plugins option of the function that sends the value.
  3. Pass the same plugin to the function that decodes the value.
JavaScript
import { serializeAsync } from 'seroval';
import { BlobPlugin } from 'seroval-plugins/web';

const blob = new Blob(['Hello'], { type: 'text/plain' });

await serializeAsync(blob, { plugins: [BlobPlugin] });

Every function takes plugins, including fromJSON, fromCrossJSON, createCrossDeserializer, Serializer, binary.serialize and binary.deserialize. The receiver needs a plugin with the same tag as the one the sender used, or decoding throws SerovalMissingPluginError.

When several plugins accept the same value, the first one in the list wins. A plugin can depend on other plugins, which are then added for you.

seroval-plugins

The seroval-plugins package has plugins for common web platform types.

npm install seroval-plugins
pnpm add seroval-plugins
yarn add seroval-plugins
bun add seroval-plugins
JavaScript
import {
  FormDataPlugin,
  HeadersPlugin,
  RequestPlugin,
  URLPlugin,
} from 'seroval-plugins/web';

Some types can only be read asynchronously. A Blob's bytes, for example, are only available through a promise. Those plugins do not work with the sync functions.

Every plugin has a binary section, so all of them work in binary mode. That includes BlobPlugin, FilePlugin and a FormData with files.

PluginTypeSyncAsyncStreamingBinary
URLPluginURL✅✅✅✅
URLSearchParamsPluginURLSearchParams✅✅✅✅
HeadersPluginHeaders✅✅✅✅
FormDataPluginFormData✅ 1✅✅ 1✅
BlobPluginBlob❌✅❌ 2✅
FilePluginFile❌✅❌ 2✅
ReadableStreamPluginReadableStream❌✅✅✅
RequestPluginRequest❌✅✅✅
ResponsePluginResponse❌✅✅✅
EventPluginEvent✅✅✅✅
CustomEventPluginCustomEvent✅✅✅✅
DOMExceptionPluginDOMException✅✅✅✅
ImageDataPluginImageData✅✅✅✅
AbortSignalPluginAbortSignal✅✅✅✅

To use every web plugin at once, put FilePlugin first. A File is also a Blob, and the first plugin that matches a value is the one used, so with BlobPlugin first a File comes back as a Blob without its name.

JavaScript
import * as web from 'seroval-plugins/web';

const plugins = [
  web.FilePlugin,
  ...Object.values(web).filter((plugin) => plugin !== web.FilePlugin),
];

Writing your own

See Writing plugins. If your plugin decodes data from a client, also read Plugin security.

Footnotes

  1. Only when the FormData contains no Blob or File entries. ↩ ↩2

  2. A Blob is built synchronously but its bytes can only be read asynchronously, so a stream cannot represent it as the same type. ↩ ↩2