Menu
CoddyTech

Counting Failed Attempts

Part of the Auth and Security section of Coddy's Node.js journey. Lesson 21 of 24.

A login limiter needs to remember failed attempts across requests. A Map stores values under keys. Use each username as a key so failures for one account do not affect another account.

const counts = new Map();
const old = counts.get('bo') ?? 0;
counts.set('bo', old + 1);

counts.get(key) returns undefined for a missing key, so the fallback starts its count at zero. Keep the Map outside the request function to preserve it while this server runs. Every request in this practice represents a failed attempt. Expiry will be a separate step; this Map currently keeps counting until Run restarts the server.

challenge icon

Challenge

Easy

This is a small practice project. Its setup is provided; edit only exercise.js.

Increment the count for the supplied username and return it in count. POST {"username":"ada"} twice to /result: counts 1 then 2. Posting bo gives 1; posting ada again gives 3.

Create the Map yourself, placing it so the second request can see the first count. Pressing Run again restarts the server and clears this in-memory store.

Try it yourself

// Create the counts store where it will survive between requests.
export function exercise({ username }) {
    return { count: 0 };
}

All lessons in Auth and Security

Practice on your own: Express playground