From a8a5085da76304463f8feed4e0392900eb53ca22 Mon Sep 17 00:00:00 2001 From: nikit Date: Mon, 6 Jul 2026 19:48:43 -0400 Subject: [PATCH] fix(habits): handle concurrent toggle race in habit log create Two concurrent toggle-on requests for the same habit+day could both observe "no existing log" and both call HabitLog.create(), tripping the unique habitId+date index and crashing with an unhandled 500 on the losing request. Catch the duplicate-key error and report toggled:true instead, since a log exists either way. Fixes #1 --- src/app/api/habits/[id]/log/route.ts | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/app/api/habits/[id]/log/route.ts b/src/app/api/habits/[id]/log/route.ts index c1e7838..12f1e35 100644 --- a/src/app/api/habits/[id]/log/route.ts +++ b/src/app/api/habits/[id]/log/route.ts @@ -39,11 +39,19 @@ export async function POST( return NextResponse.json({ toggled: false }); } - await HabitLog.create({ - habitId: id, - userId, - date, - }); - - return NextResponse.json({ toggled: true }, { status: 201 }); + try { + await HabitLog.create({ + habitId: id, + userId, + date, + }); + return NextResponse.json({ toggled: true }, { status: 201 }); + } catch (err: unknown) { + // Concurrent request created the log first — the unique habitId+date + // index rejects our insert, but a log now exists either way. + if (err && typeof err === "object" && (err as { code?: number }).code === 11000) { + return NextResponse.json({ toggled: true }, { status: 200 }); + } + throw err; + } }