Hooks

Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a beforeUpdate hook.

Note: You can’t use hooks with instances. Hooks are used with models.

Available hooks

Sequelize provides a lot of hooks. The full list can be found in directly in the source code - lib/hooks.js.

Hooks firing order

The diagram below shows the firing order for the most common hooks.

*Note: this list is not exhaustive.*

  1. (1)
  2. beforeBulkCreate(instances, options)
  3. beforeBulkDestroy(options)
  4. beforeBulkUpdate(options)
  5. (2)
  6. beforeValidate(instance, options)
  7. [... validation happens ...]
  8. (3)
  9. afterValidate(instance, options)
  10. validationFailed(instance, options, error)
  11. (4)
  12. beforeCreate(instance, options)
  13. beforeDestroy(instance, options)
  14. beforeUpdate(instance, options)
  15. beforeSave(instance, options)
  16. beforeUpsert(values, options)
  17. [... creation/update/destruction happens ...]
  18. (5)
  19. afterCreate(instance, options)
  20. afterDestroy(instance, options)
  21. afterUpdate(instance, options)
  22. afterSave(instance, options)
  23. afterUpsert(created, options)
  24. (6)
  25. afterBulkCreate(instances, options)
  26. afterBulkDestroy(options)
  27. afterBulkUpdate(options)

Declaring Hooks

Arguments to hooks are passed by reference. This means, that you can change the values, and this will be reflected in the insert / update statement. A hook may contain async actions - in this case the hook function should return a promise.

There are currently three ways to programmatically add hooks:

  1. // Method 1 via the .init() method
  2. class User extends Model {}
  3. User.init({
  4. username: DataTypes.STRING,
  5. mood: {
  6. type: DataTypes.ENUM,
  7. values: ['happy', 'sad', 'neutral']
  8. }
  9. }, {
  10. hooks: {
  11. beforeValidate: (user, options) => {
  12. user.mood = 'happy';
  13. },
  14. afterValidate: (user, options) => {
  15. user.username = 'Toni';
  16. }
  17. },
  18. sequelize
  19. });
  20. // Method 2 via the .addHook() method
  21. User.addHook('beforeValidate', (user, options) => {
  22. user.mood = 'happy';
  23. });
  24. User.addHook('afterValidate', 'someCustomName', (user, options) => {
  25. return Promise.reject(new Error("I'm afraid I can't let you do that!"));
  26. });
  27. // Method 3 via the direct method
  28. User.beforeCreate(async (user, options) => {
  29. const hashedPassword = await hashPassword(user.password);
  30. user.password = hashedPassword;
  31. });
  32. User.afterValidate('myHookAfter', (user, options) => {
  33. user.username = 'Toni';
  34. });

Removing hooks

Only a hook with name param can be removed.

  1. class Book extends Model {}
  2. Book.init({
  3. title: DataTypes.STRING
  4. }, { sequelize });
  5. Book.addHook('afterCreate', 'notifyUsers', (book, options) => {
  6. // ...
  7. });
  8. Book.removeHook('afterCreate', 'notifyUsers');

You can have many hooks with same name. Calling .removeHook() will remove all of them.

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 (on Sequelize constructor options)

  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. const User = sequelize.define('User', {});
  2. const Project = sequelize.define('Project', {}, {
  3. hooks: {
  4. beforeCreate() {
  5. // Do other stuff
  6. }
  7. }
  8. });
  9. await User.create({}); // Runs the global hook
  10. await Project.create({}); // Runs its own hook (because the global hook is overwritten)

Permanent Hooks (with sequelize.addHook)

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

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

  1. const User = sequelize.define('User', {});
  2. const Project = sequelize.define('Project', {}, {
  3. hooks: {
  4. beforeCreate() {
  5. // Do other stuff
  6. }
  7. }
  8. });
  9. await User.create({}); // Runs the global hook
  10. await Project.create({}); // Runs its own hook, followed by the global hook

Permanent hooks may also be defined in the options passed to the Sequelize constructor:

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

Note that the above is not the same as the Default Hooks mentioned above. That one uses the define option of the constructor. This one does not.

Connection Hooks

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

  • sequelize.beforeConnect(callback)
    • The callback has the form async (config) => /* ... */
  • sequelize.afterConnect(callback)
    • The callback has the form async (connection, config) => /* ... */
  • sequelize.beforeDisconnect(callback)
    • The callback has the form async (connection) => /* ... */
  • sequelize.afterDisconnect(callback)
    • The callback has the form async (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(async (config) => {
  2. config.password = await getAuthToken();
  3. });

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

Instance hooks

The following hooks will emit whenever you’re editing a single object:

  • beforeValidate
  • afterValidate / validationFailed
  • beforeCreate / beforeUpdate / beforeSave / beforeDestroy
  • afterCreate / afterUpdate / afterSave / afterDestroy
  1. User.beforeCreate(user => {
  2. if (user.accessLevel > 10 && user.username !== "Boss") {
  3. throw new Error("You can't grant this user an access level above 10!");
  4. }
  5. });

The following example will throw an error:

  1. try {
  2. await User.create({ username: 'Not a Boss', accessLevel: 20 });
  3. } catch (error) {
  4. console.log(error); // You can't grant this user an access level above 10!
  5. };

The following example will be successful:

  1. const user = await User.create({ username: 'Boss', accessLevel: 20 });
  2. console.log(user); // user object with username 'Boss' and accessLevel of 20

Model hooks

Sometimes you’ll be editing more than one record at a time by using methods like bulkCreate, update and destroy. The following hooks will emit whenever you’re using one of those methods:

  • YourModel.beforeBulkCreate(callback)
    • The callback has the form (instances, options) => /* ... */
  • YourModel.beforeBulkUpdate(callback)
    • The callback has the form (options) => /* ... */
  • YourModel.beforeBulkDestroy(callback)
    • The callback has the form (options) => /* ... */
  • YourModel.afterBulkCreate(callback)
    • The callback has the form (instances, options) => /* ... */
  • YourModel.afterBulkUpdate(callback)
    • The callback has the form (options) => /* ... */
  • YourModel.afterBulkDestroy(callback)
    • The callback has the form (options) => /* ... */

Note: methods like bulkCreate do not emit individual hooks by default - only the bulk hooks. However, if you want individual hooks to be emitted as well, you can pass the { individualHooks: true } option to the query call. However, this can drastically impact performance, depending on the number of records involved (since, among other things, all instances will be loaded into memory). Examples:

  1. await Model.destroy({
  2. where: { accessLevel: 0 },
  3. individualHooks: true
  4. });
  5. // This will select all records that are about to be deleted and emit `beforeDestroy` and `afterDestroy` on each instance.
  6. await Model.update({ username: 'Tony' }, {
  7. where: { accessLevel: 0 },
  8. individualHooks: true
  9. });
  10. // This will select all records that are about to be updated and emit `beforeUpdate` and `afterUpdate` on each instance.

If you use Model.bulkCreate(...) with the updateOnDuplicate option, changes made in the hook to fields that aren’t given in the updateOnDuplicate array will not be persisted to the database. However it is possible to change the updateOnDuplicate option inside the hook if this is what you want.

  1. User.beforeBulkCreate((users, options) => {
  2. for (const user of users) {
  3. if (user.isMember) {
  4. user.memberSince = new Date();
  5. }
  6. }
  7. // Add `memberSince` to updateOnDuplicate otherwise it won't be persisted
  8. if (options.updateOnDuplicate && !options.updateOnDuplicate.includes('memberSince')) {
  9. options.updateOnDuplicate.push('memberSince');
  10. }
  11. });
  12. // Bulk updating existing users with updateOnDuplicate option
  13. await Users.bulkCreate([
  14. { id: 1, isMember: true },
  15. { id: 2, isMember: false }
  16. ], {
  17. updateOnDuplicate: ['isMember']
  18. });

Associations

For the most part hooks will work the same for instances when being associated.

One-to-One and One-to-Many associations

  • When using add/set mixin methods the beforeUpdate and afterUpdate hooks will run.

  • The beforeDestroy and afterDestroy hooks will only be called on associations that have onDelete: 'CASCADE' and hooks: true. For example:

  1. class Projects extends Model {}
  2. Projects.init({
  3. title: DataTypes.STRING
  4. }, { sequelize });
  5. class Tasks extends Model {}
  6. Tasks.init({
  7. title: DataTypes.STRING
  8. }, { sequelize });
  9. Projects.hasMany(Tasks, { onDelete: 'CASCADE', hooks: true });
  10. Tasks.belongsTo(Projects);

This code will run beforeDestroy and afterDestroy hooks on the Tasks model.

Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute:

  1. DELETE FROM `table` WHERE associatedIdentifier = associatedIdentifier.primaryKey

However, adding hooks: true explicitly tells Sequelize that optimization is not of your concern. Then, Sequelize will first perform a SELECT on the associated objects and destroy each instance, one by one, in order to be able to properly call the hooks (with the right parameters).

Many-to-Many associations

  • When using add mixin methods for belongsToMany relationships (that will add one or more records to the junction table) the beforeBulkCreate and afterBulkCreate hooks in the junction model will run.

    • If { individualHooks: true } was passed to the call, then each individual hook will also run.
  • When using remove mixin methods for belongsToMany relationships (that will remove one or more records to the junction table) the beforeBulkDestroy and afterBulkDestroy hooks in the junction model will run.

    • If { individualHooks: true } was passed to the call, then each individual hook will also run.

If your association is Many-to-Many, you may be interested in firing hooks on the through model when using the remove call. Internally, sequelize is using Model.destroy resulting in calling the bulkDestroy instead of the before/afterDestroy hooks on each through instance.

Hooks and Transactions

Many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction is specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:

  1. User.addHook('afterCreate', async (user, options) => {
  2. // We can use `options.transaction` to perform some other call
  3. // using the same transaction of the call that triggered this hook
  4. await User.update({ mood: 'sad' }, {
  5. where: {
  6. id: user.id
  7. },
  8. transaction: options.transaction
  9. });
  10. });
  11. await sequelize.transaction(async t => {
  12. await User.create({
  13. username: 'someguy',
  14. mood: 'happy',
  15. transaction: t
  16. });
  17. });

If we had not included the transaction option in our call to User.update in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.

Internal Transactions

It is very important to recognize that sequelize may make use of transactions internally for certain operations such as Model.findOrCreate. If your hook functions execute read or write operations that rely on the object’s presence in the database, or modify the object’s stored values like the example in the preceding section, you should always specify { transaction: options.transaction }:

  • If a transaction was used, then { transaction: options.transaction } will ensure it is used again;
  • Otherwise, { transaction: options.transaction } will be equivalent to { transaction: undefined }, which won’t use a transaction (which is ok).

This way your hooks will always behave correctly.