Global / universal hooks

Global hooks are hooks which are run for all models. They can define behaviours that you want for all your models, and are especially useful for plugins. They can be defined in two ways, which have slightly different semantics:

Default Hooks (Sequelize.options.define)

  1. const sequelize = new Sequelize(..., {
  2. define: {
  3. hooks: {
  4. beforeCreate: () => {
  5. // Do stuff
  6. }
  7. }
  8. }
  9. });

This adds a default hook to all models, which is run if the model does not define its own beforeCreate hook:

  1. class User extends Model {}
  2. User.init({}, { sequelize });
  3. class Project extends Model {}
  4. Project.init({}, {
  5. hooks: {
  6. beforeCreate: () => {
  7. // Do other stuff
  8. }
  9. },
  10. sequelize
  11. });
  12. User.create() // Runs the global hook
  13. Project.create() // Runs its own hook (because the global hook is overwritten)

Permanent Hooks (Sequelize.addHook)

  1. sequelize.addHook('beforeCreate', () => {
  2. // Do stuff
  3. });

This hook is always run before create, regardless of whether the model specifies its own beforeCreate hook. Local hooks are always run before global hooks:

  1. class User extends Model {}
  2. User.init({}, { sequelize });
  3. class Project extends Model {}
  4. Project.init({}, {
  5. hooks: {
  6. beforeCreate: () => {
  7. // Do other stuff
  8. }
  9. },
  10. sequelize
  11. });
  12. User.create() // Runs the global hook
  13. Project.create() // Runs its own hook, followed by the global hook

Permanent hooks may also be defined in Sequelize.options:

  1. new Sequelize(..., {
  2. hooks: {
  3. beforeCreate: () => {
  4. // do stuff
  5. }
  6. }
  7. });

Connection Hooks

Sequelize provides four hooks that are executed immediately before and after a database connection is obtained or released:

  1. beforeConnect(config)
  2. afterConnect(connection, config)
  3. beforeDisconnect(connection)
  4. afterDisconnect(connection)

These hooks can be useful if you need to asynchronously obtain database credentials, or need to directly access the low-level database connection after it has been created.

For example, we can asynchronously obtain a database password from a rotating token store, and mutate Sequelize's configuration object with the new credentials:

  1. sequelize.beforeConnect((config) => {
  2. return getAuthToken()
  3. .then((token) => {
  4. config.password = token;
  5. });
  6. });

These hooks may only be declared as a permanent global hook, as the connection pool is shared by all models.