What is the difference between put() and add() in IndexedDB?
Ask by Rana Sunny
Updated 03 Jul 2025
In IndexedDB, both
put()andadd()are used to store data in an object store, but they have different behaviors when it comes to existing records.add()
Adds a new record only if the key does not already exist. Throws an error if a record with the same key already exists. Used when you want to prevent overwriting existing data.
Example:
put()
Adds a new record or updates an existing record with the same key. Overwrites if the key already exists. Used when you want to upsert (insert or update) data.
Example:
Summary Table
add()put()Use Guidelines
add()when:put()when:Here are code examples with error handling for both
add()andput()in IndexedDB:Setup (for both examples)
Using
add()(fails on duplicate key)Using
put()(updates if exists)Note:
add()example, trying to insertid: 1again will cause aConstraintError.put()example, it will silently overwrite ifid: 1already exists.