I’m working on a Rails application that uses Devise for user authentication. I need to automatically send user details to an external webhook service whenever someone logs into my app.
I’ve been searching for a solution but can’t find a clear way to capture the user’s email and other info during the login process and then POST it to a webhook URL. Has anyone implemented something similar?
I’m thinking I might need to use some kind of callback or hook in Devise, but I’m not sure which approach would work best. Any suggestions on how to achieve this functionality would be really helpful.
devise callbacks are great for this! I use after_database_authentication in my user model – just create a method and it triggers on every successful login. I call my webhook service there but have it in a rescue block to prevent login issues if the webhook is down. much simpler than messing with controller overrides.
You can also use Devise’s callback system with Warden hooks. Just add a custom hook in your Rails initializer that triggers after authentication. I created a config/initializers/warden_hooks.rb file and used Warden::Manager.after_authentication to grab the user data. This beats overriding controller methods because it catches every authentication event, not just manual logins. Handle webhook timeouts though - I got burned when our third-party service went down and users couldn’t log in. Add a retry mechanism and always rescue from connection errors.
I dealt with this same issue about six months ago. Here’s what worked: override the after_sign_in_path_for method in ApplicationController and trigger your webhook from there. Grab the user object and send it to your webhook service using a background job - this keeps login fast. I used Sidekiq but any job processor works. Make sure webhook failures don’t break user login if your external service goes down. Also, add basic auth or signing to your webhook payload for security.