How To Intercept Pocketbase Events Using JavaScript

No Comments
Published: 10.03.2024

Learn how to intercept Pocketbase events using JavaScript by sending an email to the user when they change some data on their user profile. This can be useful in case you want to notify the user about a password or email change to verify that it was them.

Intercept the Pocketbase OnUpdate Event using JavaScript

To intercept the Pocketbase event, we will create a folder called backend/pb_hooks with a file called checkUser.pb.js. You always need to create a file *.pb.js to create a new hook. Inside the hook, we will use a comment to get typing and then subscribe ourselves to the event called onRecordBeforeUpdateRequest. Inside this, we compare the old and new records and send an email to the user including which data has changed.

We have to stringify and then parse the record so that we can loop over the properties and compare them. If we do not use the parse function, we would need to access the properties using a functional call like e.record.name().

/// <reference path="../pb_data/types.d.ts" />

// before because otherwise also updated changes
onRecordBeforeUpdateRequest((e) => {
    const parse = (obj) => JSON.parse(JSON.stringify(obj));

    const original = parse(e.record?.originalCopy());
    const updated = parse(e.record?.cleanCopy());

    let changed = []
    for (const key in original) {
        if (original[key] !== updated[key]) {
            changed.push(key === "username" ? "email" : key)
        }
    }

    const message = new MailerMessage({
        from: {
            address: $app.settings().meta.senderAddress,
            name:    $app.settings().meta.senderName,
        },
        to:      [{address: e.record.email()}],
        subject: "You updated your profile!",
        html:    `<p>Hello,<br>you updated the following properties of your user profile: ${changed.toString()}`
    })

    $app.newMailClient().send(message)
}, "users")

This is just a really simple notification email that you can extend with other functionality if you need it.
You can also access the current state of the project in this repository and the branch called “course-10”.

Conclusion

In this post, you learned how to intercept Pocketbase events with JavaScript hooks by notifying the user of changes in their profile. I hope you liked the course so far.

If you have any questions, feel free to ask. If you want to stay up to date with all my posts, consider subscribing to my monthly newsletter!

Need help or want to share feedback? Join my discord community!

Discussion (0)

Add Comment

Your email address will not be published. Required fields are marked *