---
url: /reference/core/withplugins.md
---

# withPlugins

```ts
import { withPlugins } from '@signaldb/core'
```

`withPlugins(collection, ...plugins)` installs plugins on a collection. A plugin adds methods to the collection, and a package can ship one to extend collections without a change to SignalDB itself.

```ts
import { Collection, withPlugins } from '@signaldb/core'

const Posts = withPlugins(
  new Collection<Post>('posts', dataAdapter, { reactivity }),
  newest(),
  // …further plugins
)

const post = await Posts.newest()
```

`newest()` is the plugin written [below](#writing-a-plugin). For a complete plugin, see [`@signaldb/search`](/reference/search/), which adds a reactive `search()` method.

`withPlugins` returns the collection you passed in. Only its type differs, because it knows about the added methods. Use the returned value, even though it is the same object.

* The plugins are installed in the order they are passed.
* A plugin that would add a method the collection already has, either as one of its own members or from a plugin installed before, makes `withPlugins` throw.
* [`dispose()`](/reference/core/collection/#dispose) disposes the plugins first, one after another, while the collection is still usable, and the collection afterwards.

## Writing a plugin

A plugin is a function that receives the collection and a context, and returns the methods it adds along with an optional `dispose` function.

```ts
import type { CollectionPlugin } from '@signaldb/core'

type CollectionPlugin<Methods extends object> = (
  collection: Collection<any, any, any, any>,
  context: { reactivity?: ReactivityAdapter },
) => {
  methods: Methods,
  dispose?: () => void | Promise<void>,
}
```

`context.reactivity` is the collection's [reactivity adapter](/reference/core/createreactivityadapter/), for plugins whose methods are reactive themselves.

A method that needs the collection's item types declares the collection through a `this` parameter. TypeScript then resolves the types at the call site, so they are correct even for a collection created with an explicit item type.

```ts
import type { Collection, CollectionPlugin } from '@signaldb/core'

type AnyCollection = Collection<any, any, any, any>
type ItemOf<C> = C extends Collection<any, any, any, infer U> ? U : never

const newest = (): CollectionPlugin<{
  newest<C extends AnyCollection>(this: C): Promise<ItemOf<C> | undefined>,
}> => collection => ({
  methods: {
    newest: () => collection.findOne({}, { sort: { createdAt: -1 }, async: true }),
  },
})

const Posts = withPlugins(new Collection<Post>('posts', dataAdapter), newest())
const post = await Posts.newest() // Post | undefined
```

The methods are called on the collection, but they should not rely on `this` at runtime. Use the `collection` argument instead, as above.
