Skip to content

Getting started

Create a collection, seed it with records, and query them.

Install ​

Add @msw/data as a dependency to your project:

sh
npm install @msw/data --save-dev
sh
pnpm add @msw/data --save-dev

Create a collection ​

You start by defining a data collection. A collection holds records of the same shape, described by a schema.

ts
import { 
Collection
} from '@msw/data'
import { z } from 'zod' const
users
= new
Collection
({
schema
: z.
object
({
id
: z.
number
(),
name
: z.
string
(),
}), })

Above, we are using Zod to describe the schema for the users collection. You can use whichever Standard Schema compliant library of your choice instead.

Seed the collection ​

Next, let's put some values into the collection. Those values are called records. Create individual records via the .create() method or a bunch of them with .createMany():

ts
await 
users
.
create
({
id
: 1,
name
: 'John' })
await
users
.
createMany
(5, (
index
) => ({
id
:
index
+ 1,
name
: faker.person.firstName(),
}))

Combine .createMany() with tools like Faker for random values in your records.

Use the collection ​

From this point on, you can use the users collection for anything data-related: create more records, query them, define relations to other collections, update and delete records.

ts
const 
john
=
users
.
findFirst
((
q
) =>
q
.
where
({
name
: 'John' }))

Learn more about what you can do with the library in the following sections: