Skip to content

Function: encode()

ts
function encode(schema: Schema, options: EncoderOptions): string;

Encodes a validation schema into a compressed, base64-encoded string for transport between environments.

This function serializes a validation schema description along with version information, compresses it using zlib, and encodes it as a base64 string. This enables efficient transfer of validation schemas between frontend and backend environments while maintaining version compatibility.

The encoded string includes:

  • Current library version for compatibility checking
  • Complete schema description from schema.describe()
  • Zlib compression for minimal payload size
  • Base64 encoding for web-safe transport

Parameters

ParameterTypeDescription
schemaSchemaThe validation schema to encode
optionsEncoderOptionsEncoding options. withDatabase defaults to FALSE, which strips database connections, external database rules, and database filter functions from the output so the result is safe to send to a browser. Set it to true only for trusted backend-to-backend transfer, where serialized functions are preserved and rehydrated on decode.

Returns

string

A compressed, base64-encoded string representing the schema

Examples

typescript
import Joi from "joi";
import { encode } from "./utils";

const schema = Joi.object({
  name: Joi.string().required(),
  age: Joi.number().min(0),
});

const encoded = encode(schema);
// Returns: "eJyrVkosLcmIz8nPS1WyUvJIzcnJT..."
typescript
// Backend
const validationSchema = Joi.object({
  email: Joi.string().email().required(),
});
const encodedSchema = encode(validationSchema);

// Send to frontend via API
response.json({ schema: encodedSchema });

// Frontend can then decode and use the same validation

See

decode For decoding schemas from encoded strings