---
title: "Emit and Listen to Socket.IO Events in FeathersJS"
date: 2022-12-12T15:34:01.000Z
author: Z.SHINCHVEN
tags: [FeathersJS, Socket.IO]
canonical: https://atlassc.net/2022/12/13/emit-and-listen-to-socket-io-events-in-feathersjs
---
FeatherJS uses [Socket.IO](https://socket.io/) to build real-time applications. With it, we can [push messages](https://docs.feathersjs.com/api/events.html#events) from server side to client side. 

## Events for RESTful Service

FeathersJS has implemented basic events for RESTful service like: 
- created
- updated
- patched
- removed

It is configured in `src/channels.ts` by default, you don't have to emit these events yourself.

## Emit Event Programmatically

To emit an event programmatically for a custom service, we can use `service.emit` method.

```ts
app.service('messages').emit('created', { text: 'A new message' });
```

## Emit Custom Event

If you your event is not in the events list for RESTful service, you should declare it in your service, then use it to emit event.

```ts
class Message{
  events = ['custom-event'];
}

app.service('messages').emit('custom-event', { text: 'A new message' });
```

## Listen to Event

At client side, we can listen to event by using `service.on` method.

```ts
// Event for RESTful service
app.service('messages').on('created', message => console.log('Created a new message', message));
// Custom event
app.service('messages').on('custom-event', message => console.log('Custom event', message));
```

## Remove Event Listener

To remove event listener, we can use `service.removeListener` method.

It is a good practice to remove event listener when your component is unmounted.

```ts
// Make a reference to the listener
const listener = message => console.log('Custom event', message);
// Mount the listener
app.service('messages').on('custom-event', listener);
// Remove the listener
app.service('messages').removeListener('custom-event', listener);
```
