Don't expose primary id's with Rails' dom_id

Published at Leave your comment

UPDATE: I have sunsetted stealth_dom_id and now suggest the method outlined in this article.

If you use Hotwire with Rails, you have most likely used dom_id. It’s a clever, little helper to give a unique id to an element. This helps to easily target an element with Turbo Streams (to update, append or delete).

You use it like this:

dom_id(User)          # => "new_user"
dom_id(User.find(42)) # => "user_42"

It is this last example I have issues with. As it exposes the primary id of that record. Depending on your app, you might not care, but when you run a (SaaS) business, this might be sensitive business information you don’t want exposed.

So I created a little gem, called stealth_dom_id.

It’s based on an a small class I added in my lib folder for years (there might be more candidates in there for gems 🤫). It works like this:

dom_id(User.find(42), attribute: :public_id) # "user_a1b2c3"

You can also, just like with the unstealthy dom_id, pass a prefix attribute:

dom_id(User.find(42), :admin, attribute: :public_id) # "admin_user_a1b2c3"

If you use dom_id in your Rails projects, I am sure you will love it. Check it out on GitHub.

💬 Over to you…

What did you like about this article? Learned something knew? Found something is missing or even broken? 🫣 Let me (and others) know!

Comments are powered by Chirp Form

More articles like this on modern Rails & frontend? Get them first in your inbox.
JavaScript for Rails Developers
Make JS your 2nd favorite language