Open
Description
Description
The callback to jwt.sign() is executed twice when there is an error Bad "options.issuer" option. The payload already has an "iss" property. I would expect the callback to only be executed once.
Reproduction
// a.mjs
import jwt from "jsonwebtoken";
jwt.sign(
{
iss: "bar",
iat: 1757476476,
},
"secret",
{
algorithm: "HS256",
issuer: "foo",
},
(err, asyncSigned) => {
console.log("callback called:", asyncSigned ?? err?.message);
},
);$> npm init -y && npm add jsonwebtoken
$> node a.mjs
callback called: Bad "options.issuer" option. The payload already has an "iss" property.
callback called: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJiYXIiLCJpYXQiOjE3NTc0NzY0NzZ9.TkSecbZDocHnjwnuDhQRXNvRkxsERNGBkRc6P0wHlNY
Notice that "callback called" is printed twice, while I would expect it to be printed only once.
Environment
jsonwebtoken 9.0.2 on Darwin 24.6.0 arm64 arm
Other information
It looks like the error is here:
Lines 217 to 225 in bc28861
| Object.keys(options_to_payload).forEach(function (key) { | |
| const claim = options_to_payload[key]; | |
| if (typeof options[key] !== 'undefined') { | |
| if (typeof payload[claim] !== 'undefined') { | |
| return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); | |
| } | |
| payload[claim] = options[key]; | |
| } | |
| }); |
Typically, return failure() throws which exits the forEach and the function. But when a callback is provided, it only returns from the forEach. The rest of the keys are checked and the rest of the function still runs.
Reacted by Gajanan Mundhe
Metadata
Metadata
Assignees
Labels
No labels
Activity
maishivamhoo123 commentedon Nov 7, 2025
@pfgithub I think you are right because forEach will not return even after getting an error.
I think we should use a for loop here.
Something like:
for (const key of Object.keys(options_to_payload)) {
//same logic
}
This way the function will properly return after the first error and won’t call the callback twice.
Am I right?
@team can you please assign this issue to me
fix: prevent callback from being called twice on payload claim conflict
fix: prevent double callback invocation on payload conflict
fix: prevent callback from being called twice on payload conflict
azender1 commentedon Mar 30, 2026
Bugs like this are easy to underestimate because “callback executed twice” sounds cosmetic until the callback is wired to a mutation.
At that point it stops being just a library bug and becomes a duplicate-execution risk.
The safest pattern I’ve found around this class of problem is:
treat the callback-triggered mutation as a logical operation with a stable request ID
persist a durable execution receipt before / at the side-effect boundary
make re-entry return the prior result instead of executing again
Otherwise any duplicate callback path can leak into duplicate writes, notifications, token persistence, or external API calls.