Updated:

1. Give a totem

/give @p totem_of_undying

Same ID on Java and Bedrock. Totems do not stack unless you set max_stack_size (Java 1.20.5+, see the stack size command).

2. Put it in the offhand

/item replace entity @p weapon.offhand with totem_of_undying

On Bedrock:

/replaceitem entity @p slot.weapon.offhand 0 totem_of_undying

See the item replace command.

3. Auto refill (Java 1.20.5+)

/execute as @a unless items entity @s weapon.offhand totem_of_undying run item replace entity @s weapon.offhand with totem_of_undying

Run it in a repeating command block. Whatever else was in the offhand is replaced.

4. Any item as a totem (Java 1.21.2+)

/give @p golden_apple[death_protection={}]

The death_protection component makes any item work like a totem: hold it when you would die and it saves you, then it is used up. You can also add effects with death_effects inside it, the same way the real totem gives Regeneration and Absorption.

5. Count totem uses (Java)

/scoreboard objectives add totem minecraft.used:minecraft.totem_of_undying
/scoreboard objectives setdisplay sidebar totem

The score goes up by one each time a player pops a totem. Show it in the sidebar to see who came closest to dying in a PvP match.

6. Give a mob a totem (Java 1.21.5+)

/summon zombie ~ ~ ~5 {equipment:{offhand:{id:"minecraft:totem_of_undying",count:1}}}

A mob holding a totem survives one death, just like a player. Use HandItems on 1.21.4 and earlier.

Troubleshooting

Check your command

The Command Error Doctor checks common syntax mistakes in your browser.