> ## Documentation Index
> Fetch the complete documentation index at: https://www.orionjs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Schema Serialization

> Learn about serializing schemas for client-side validation

Orionjs schemas can be serialized and sent to the client for use in form validation, GraphQL introspection, and more.

## Basic Serialization Example

```typescript theme={null}
import {schemaWithName, InferSchemaType, serializeSchema} from '@orion-js/schema'

export const UserSchema = schemaWithName('UserSchema', {
  name: {type: String, min: 3},
  email: {type: String, optional: true},
  age: {type: Number, min: 18}
})

export type UserType = InferSchemaType<typeof UserSchema>

// Serialize the schema to JSON
const serializedSchema = serializeSchema(UserSchema)
console.log(serializedSchema)
```

The output will be a JSON representation of the schema:

```json theme={null}
{
  "name": {
    "type": "string",
    "min": 3
  },
  "email": {
    "type": "string",
    "optional": true
  },
  "age": {
    "type": "number",
    "min": 18
  }
}
```

## Using Serialized Schemas in the Client

You can use the serialized schema for client-side validation in frontend applications:

```typescript theme={null}
import {serializeSchema} from '@orion-js/schema'
import {UserSchema} from './schemas/UserSchema'

// In your API endpoint
app.get('/schemas/user', (req, res) => {
  res.json(serializeSchema(UserSchema))
})
```

On the client side, you can use this schema with form libraries or build custom validation:

```javascript theme={null}
// Client-side code
async function fetchUserSchema() {
  const response = await fetch('/schemas/user')
  return response.json()
}

async function validateUserForm(formData) {
  const schema = await fetchUserSchema()
  return validateAgainstSchema(formData, schema) // Simplified example
}
```

## Schema Serialization with Nested Schemas

When a schema includes nested schemas, these will also be serialized:

```typescript theme={null}
import {schemaWithName, InferSchemaType} from '@orion-js/schema'

export const AddressSchema = schemaWithName('AddressSchema', {
  street: {type: String},
  city: {type: String}
})

export const ContactSchema = schemaWithName('ContactSchema', {
  name: {type: String},
  address: {type: AddressSchema}
})

// Serialized schema will include the nested AddressSchema structure
const serializedContact = serializeSchema(ContactSchema)
```

## Key Benefits

1. **Consistent validation rules** across server and client
2. **DRY principle** - define schema once, use everywhere
3. **Type safety** throughout your application
4. **Better UX** - validate forms before submission

## Performance Tips

* Cache serialized schemas to avoid redundant processing
* Only serialize fields needed for client validation
* Consider security implications of exposing validation rules
