Don't expose primary id's with Rails' dom_id
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.
Want to read me more?
-
Rails dom_id helper without exposing the primary id
Rails' dom_id is small, but smart little helper for your Turbo-powered Rails app. -
How do Turbo Streams Work (behind the scenes)
Turbo Streams uses a few standard features around custom elements. available in any modern browsers. Learn how Turbo Streams work behind the scenes. -
How to order attributes on HTML elements
Having a consistent order of HTML attributes, leaves you with mental space to think about the business logic and minimizes discussions with your team.
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
{{comment}}