superstruct
A simple and composable way to validate data in JavaScript (and TypeScript).
Top Related Projects
TypeScript-first schema validation with static type inference
Dead simple Object schema validation
Runtime type system for IO decoding/encoding
Runtime validation for static types
Decorator-based property validation for classes.
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
Quick Overview
Superstruct is a lightweight and flexible validation library for JavaScript. It allows developers to define complex data structures and validate JavaScript objects against these structures. Superstruct is designed to be simple to use, yet powerful enough to handle complex validation scenarios.
Pros
- Easy to learn and use, with a clean and intuitive API
- Highly customizable with support for custom types and validators
- Excellent TypeScript support, providing strong type inference
- Small bundle size, making it suitable for both browser and Node.js environments
Cons
- Less feature-rich compared to some more established validation libraries
- Limited built-in validators, requiring custom implementations for complex scenarios
- Documentation could be more comprehensive, especially for advanced use cases
Code Examples
- Basic validation:
import { object, string, number, assert } from 'superstruct'
const User = object({
name: string(),
age: number(),
})
const user = {
name: 'John Doe',
age: 30,
}
assert(user, User)
// Passes validation
- Custom validator:
import { define, string } from 'superstruct'
const Email = define('Email', (value) => {
if (typeof value !== 'string') return false
return /^[^@]+@[^@]+\.[^@]+$/.test(value)
})
const UserWithEmail = object({
name: string(),
email: Email,
})
assert({ name: 'John', email: 'john@example.com' }, UserWithEmail)
// Passes validation
- Nested structures:
import { object, string, array, assert } from 'superstruct'
const Address = object({
street: string(),
city: string(),
country: string(),
})
const User = object({
name: string(),
addresses: array(Address),
})
const user = {
name: 'Jane Doe',
addresses: [
{ street: '123 Main St', city: 'Anytown', country: 'USA' },
{ street: '456 Elm St', city: 'Othertown', country: 'Canada' },
],
}
assert(user, User)
// Passes validation
Getting Started
To use Superstruct in your project, first install it:
npm install superstruct
Then, import and use it in your code:
import { object, string, number, assert } from 'superstruct'
const Person = object({
name: string(),
age: number(),
})
const person = { name: 'Alice', age: 25 }
try {
assert(person, Person)
console.log('Validation passed')
} catch (error) {
console.error('Validation failed:', error.message)
}
This example defines a simple Person
structure and validates an object against it. If the validation passes, it will log a success message; otherwise, it will catch the error and log the failure message.
Competitor Comparisons
TypeScript-first schema validation with static type inference
Pros of Zod
- Better TypeScript integration with automatic type inference
- More extensive validation features, including async validation
- Larger ecosystem with plugins and integrations
Cons of Zod
- Slightly more complex API, steeper learning curve
- Larger bundle size compared to Superstruct
Code Comparison
Zod:
const UserSchema = z.object({
name: z.string(),
age: z.number().min(18),
email: z.string().email(),
});
const user = UserSchema.parse(data);
Superstruct:
const User = object({
name: string(),
age: number().min(18),
email: string().email(),
});
const user = create(data, User);
Both libraries offer similar functionality for defining and validating schemas. Zod provides more advanced features and better TypeScript integration, while Superstruct has a simpler API and smaller footprint. The choice between them depends on project requirements and developer preferences.
Dead simple Object schema validation
Pros of Yup
- More extensive built-in validation methods and customization options
- Better TypeScript support with stronger type inference
- Larger community and ecosystem with more third-party extensions
Cons of Yup
- Slightly larger bundle size and runtime overhead
- Less flexible when defining complex, nested schemas
- Steeper learning curve for advanced use cases
Code Comparison
Yup:
import * as Yup from 'yup';
const schema = Yup.object().shape({
name: Yup.string().required(),
age: Yup.number().positive().integer().required(),
});
Superstruct:
import { object, string, number } from 'superstruct';
const schema = object({
name: string(),
age: number(),
});
Both Yup and Superstruct are popular libraries for object schema validation in JavaScript. Yup offers more built-in validation methods and better TypeScript support, making it suitable for complex validation scenarios. However, it comes with a slightly larger bundle size and can be more challenging to learn for advanced use cases.
Superstruct, on the other hand, provides a simpler API and is more lightweight, making it easier to get started with and integrate into projects. It's particularly well-suited for applications where performance and bundle size are critical factors. However, it may require more custom code for complex validation scenarios compared to Yup.
Runtime type system for IO decoding/encoding
Pros of io-ts
- Strong integration with TypeScript, leveraging its type system
- Supports functional programming paradigms and composition
- Provides runtime type checking and validation
Cons of io-ts
- Steeper learning curve, especially for developers unfamiliar with functional programming
- More verbose syntax compared to Superstruct
- Limited built-in types, requiring more custom type definitions
Code Comparison
io-ts:
import * as t from 'io-ts'
const Person = t.type({
name: t.string,
age: t.number
})
const result = Person.decode({ name: 'Alice', age: 30 })
Superstruct:
import { object, string, number } from 'superstruct'
const Person = object({
name: string(),
age: number()
})
const result = Person.validate({ name: 'Alice', age: 30 })
Both libraries provide runtime validation, but io-ts focuses on functional programming patterns and TypeScript integration, while Superstruct offers a more straightforward API. io-ts excels in type-safe operations and composability, whereas Superstruct is generally easier to pick up and use, especially for developers coming from a more traditional object-oriented background.
Runtime validation for static types
Pros of Runtypes
- Focuses on runtime type checking, providing stronger guarantees during execution
- Supports more advanced types like unions, intersections, and branded types
- Offers automatic TypeScript type inference from runtime checks
Cons of Runtypes
- Less flexible in terms of custom validation rules
- Smaller community and ecosystem compared to Superstruct
- May have a steeper learning curve for complex type definitions
Code Comparison
Runtypes:
const Person = Record({
name: String,
age: Number,
});
const person = Person.check({ name: "Alice", age: 30 });
Superstruct:
const Person = object({
name: string(),
age: number(),
});
const person = create({ name: "Alice", age: 30 }, Person);
Both libraries provide similar functionality for defining and validating data structures. Runtypes focuses more on runtime type checking and advanced TypeScript integration, while Superstruct offers a more flexible and customizable validation system. The choice between them depends on specific project requirements, such as the need for runtime type guarantees versus more complex validation rules.
Decorator-based property validation for classes.
Pros of class-validator
- Designed specifically for class-based validation with decorators
- Integrates well with frameworks like TypeORM and NestJS
- Offers a wide range of built-in validation decorators
Cons of class-validator
- Limited to class-based structures, less flexible for plain objects
- Requires TypeScript and decorator support
- Can be more verbose for simple validation scenarios
Code Comparison
class-validator:
import { IsString, MinLength, IsEmail } from 'class-validator';
class User {
@IsString()
@MinLength(2)
name: string;
@IsEmail()
email: string;
}
Superstruct:
import { object, string, size, email } from 'superstruct';
const User = object({
name: size(string(), 2, Infinity),
email: email(),
});
Key Differences
- class-validator uses decorators for validation, while Superstruct uses a more functional approach
- Superstruct is more flexible, working with plain objects and various data structures
- class-validator is tailored for class-based TypeScript projects, while Superstruct is more language-agnostic
- Superstruct offers a simpler API for basic validations, but class-validator provides more built-in validators
Both libraries have their strengths, and the choice depends on project requirements, architecture, and personal preference.
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
Pros of Ajv
- Supports JSON Schema validation, offering a standardized approach
- Highly performant, especially for large datasets
- Extensive ecosystem with plugins and integrations
Cons of Ajv
- Steeper learning curve due to JSON Schema complexity
- Less intuitive for simple validation scenarios
- Larger bundle size compared to Superstruct
Code Comparison
Ajv:
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number', minimum: 0 }
},
required: ['name', 'age']
};
const validate = ajv.compile(schema);
Superstruct:
import { object, string, number, define } from 'superstruct';
const Person = object({
name: string(),
age: define('positive', number(), value => value >= 0)
});
const [error, data] = Person.validate({ name: 'John', age: 30 });
Both libraries offer robust validation capabilities, but Ajv excels in complex scenarios and performance, while Superstruct provides a more intuitive API for simpler use cases. Ajv's JSON Schema support makes it more suitable for projects requiring standardized validation, whereas Superstruct's flexibility and ease of use make it ideal for quick implementations and custom validation logic.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
A simple and composable way
to validate data in JavaScript (and TypeScript).
Usage ⢠Why? ⢠Principles ⢠Demo ⢠Examples ⢠Documentation
Superstruct makes it easy to define interfaces and then validate JavaScript data against them. Its type annotation API was inspired by Typescript, Flow, Go, and GraphQL, giving it a familiar and easy to understand API.
But Superstruct is designed for validating data at runtime, so it throws (or returns) detailed runtime errors for you or your end users. This is especially useful in situations like accepting arbitrary input in a REST or GraphQL API. But it can even be used to validate internal data structures at runtime when needed.
Usage
Superstruct allows you to define the shape of data you want to validate:
import { assert, object, number, string, array } from 'superstruct'
const Article = object({
id: number(),
title: string(),
tags: array(string()),
author: object({
id: number(),
}),
})
const data = {
id: 34,
title: 'Hello World',
tags: ['news', 'features'],
author: {
id: 1,
},
}
assert(data, Article)
// This will throw an error when the data is invalid.
// If you'd rather not throw, you can use `is()` or `validate()`.
Superstruct ships with validators for all the common JavaScript data types, and you can define custom ones too:
import { is, define, object, string } from 'superstruct'
import isUuid from 'is-uuid'
import isEmail from 'is-email'
const Email = define('Email', isEmail)
const Uuid = define('Uuid', isUuid.v4)
const User = object({
id: Uuid,
email: Email,
name: string(),
})
const data = {
id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
email: 'jane@example.com',
name: 'Jane',
}
if (is(data, User)) {
// Your data is guaranteed to be valid in this block.
}
Superstruct can also handle coercion of your data before validating it, for example to mix in default values:
import { create, object, number, string, defaulted } from 'superstruct'
let i = 0
const User = object({
id: defaulted(number(), () => i++),
name: string(),
})
const data = {
name: 'Jane',
}
// You can apply the defaults to your data while validating.
const user = create(data, User)
// {
// id: 0,
// name: 'Jane',
// }
And if you use TypeScript, Superstruct automatically ensures that your data has proper typings whenever you validate it:
import { is, object, number, string } from 'superstruct'
const User = object({
id: number(),
name: string()
})
const data: unknown = { ... }
if (is(data, User)) {
// TypeScript knows the shape of `data` here, so it is safe to access
// properties like `data.id` and `data.name`.
}
Superstruct supports more complex use cases too like defining arrays or nested objects, composing structs inside each other, returning errors instead of throwing them, and more! For more information read the full Documentation.
Why?
There are lots of existing validation librariesâjoi
, express-validator
, validator.js
, yup
, ajv
, is-my-json-valid
... But they exhibit many issues that lead to your codebase becoming hard to maintain...
-
They don't expose detailed errors. Many validators simply return string-only errors or booleans without any details as to why, making it difficult to customize the errors to be helpful for end-users.
-
They make custom types hard. Many validators ship with built-in types like emails, URLs, UUIDs, etc. with no way to know what they check for, and complicated APIs for defining new types.
-
They don't encourage single sources of truth. Many existing APIs encourage re-defining custom data types over and over, with the source of truth being spread out across your entire code base.
-
They don't throw errors. Many don't actually throw the errors, forcing you to wrap everywhere. Although helpful in the days of callbacks, not using
throw
in modern JavaScript makes code much more complex. -
They're tightly coupled to other concerns. Many validators are tightly coupled to Express or other frameworks, which results in one-off, confusing code that isn't reusable across your code base.
-
They use JSON Schema. Don't get me wrong, JSON Schema can be useful. But it's kind of like HATEOASâit's usually way more complexity than you need and you aren't using any of its benefits. (Sorry, I said it.)
Of course, not every validation library suffers from all of these issues, but most of them exhibit at least one. If you've run into this problem before, you might like Superstruct.
Which brings me to how Superstruct solves these issues...
Principles
-
Customizable types. Superstruct's power is in making it easy to define an entire set of custom data types that are specific to your application, and defined in a single place, so you have full control over your requirements.
-
Unopinionated defaults. Superstruct ships with native JavaScript types, and everything else is customizable, so you never have to fight to override decisions made by "core" that differ from your application's needs.
-
Composable interfaces. Superstruct interfaces are composable, so you can break down commonly-repeated pieces of data into components, and compose them to build up the more complex objects.
-
Useful errors. The errors that Superstruct throws contain all the information you need to convert them into your own application-specific errors easy, which means more helpful errors for your end users!
-
Familiar API. The Superstruct API was heavily inspired by Typescript, Flow, Go, and GraphQL. If you're familiar with any of those, then its schema definition API will feel very natural to use, so you can get started quickly.
Demo
Try out the live demo on CodeSandbox to get an idea for how the API works, or to quickly verify your use case:
Examples
Superstruct's API is very flexible, allowing it to be used for a variety of use cases on your servers and in the browser. Here are a few examples of common patterns...
- Basic Validation
- Custom Types
- Default Values
- Optional Values
- Composing Structs
- Throwing Errors
- Returning Errors
- Testing Values
- Custom Errors
Documentation
Read the getting started guide to familiarize yourself with how Superstruct works. After that, check out the full API reference for more detailed information about structs, types and errors...
License
This package is MIT-licensed.
Top Related Projects
TypeScript-first schema validation with static type inference
Dead simple Object schema validation
Runtime type system for IO decoding/encoding
Runtime validation for static types
Decorator-based property validation for classes.
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot