# Hooks

Ts.ED emits different events during its initialization phase (lifecycle). These lifecycle hooks provide visibility into these key life moments and the ability to act when they occur.

This schema resume the order of hooks regard to Server and Providers:

# Examples

Hooks can be used on your Server:

import {BeforeInit, Configuration} from "@tsed/common";

@Configuration({})
class Server implements BeforeInit {
  async $beforeInit(): Promise<any> {}
}
1
2
3
4
5
6

or on your Module or Service :

import {Module, BeforeInit} from "@tsed/common";

@Module()
export class MyModule implements BeforeInit {
  async $beforeInit(): Promise<any> {}
}
1
2
3
4
5
6

Note

Database connection can be performed with Asynchronous Provider since v5.26. See custom providers

Since v6.110.0, it's also possible to register hooks on custom provider:

import {Configuration, registerProvider} from "@tsed/di";
import {DatabaseConnection} from "connection-lib";

export const CONNECTION = Symbol.for("CONNECTION");

registerProvider<DatabaseConnection>({
  provide: CONNECTION,
  deps: [Configuration],
  useFactory(configuration: Configuration) {
    const options = configuration.get<any>("myOptions");

    return new DatabaseConnection(options);
  },
  hooks: {
    $onDestroy(connection) {
      // called when provider instance is destroyed
      return connection.close();
    }
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Last Updated: 5/19/2022, 2:53:00 PM

Other topics