Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: Authenticated Bookmarks API

Combine registration with hashed passwords, JWT login, per-user bookmarks, ownership checks, rate limiting and an inject test suite into one secure Fastify-style API.

The Notes API had no users. This second project adds them: people register, log in to get a token, and then manage their own bookmarks. Nobody can see or change another person's data. You will reuse ideas from the security chapter: scrypt password hashing, signed tokens, an authenticate hook, ownership checks, a login rate limit and a consistent error shape.

Fastify is not installed on this site. The runnable code uses the Fastify-like stand-in (same post, get, delete, addHook, inject shapes) and node:crypto. A real project would use @fastify/jwt, @fastify/rate-limit and JSON schemas; mappings are shown at the end. Do not copy the hand-written token code into production.

The flow

Register Email and password, hashed.
Login Returns a signed token.
Bookmarks Only your own, with Bearer.
Limits Few login tries per minute.

Four routes of auth, three of data.

1 / 2

Requirements

Route Auth Behavior
POST /register no { email, password }; password at least 10 characters; 409 if the email is taken; 201 without the hash in the answer.
POST /login no 200 with { token }; the same 401 message for unknown email and wrong password; limited to 5 attempts per window per client.
GET /bookmarks yes Only the caller's bookmarks.
POST /bookmarks yes { url, title? }; url must be an http or https URL.
DELETE /bookmarks/:id yes 204; another user's id answers 404.

The application

Read it in four layers: helpers (password hashing, token signing), the authentication hook, the routes, and the factory that wires dependencies. The clock is injected so the token expiry and the rate limit can be tested without waiting.

Node.js Bookmarks API with registration, login and ownership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the design decisions in the output: the registration answer has no password hash, both login failures read the same, javascript: URLs are refused (they would run code if a front end rendered them as links), and Bob cannot delete Ann's bookmark (he gets 404, not 403, so ids are not confirmed).

Tests for the rules that matter most

For a security-sensitive API, the most valuable tests are the negative ones: things that must not work. The next suite uses a fake clock so the token expiry and the login limit are tested instantly. The app is repeated in a trimmed form (without hashing, to keep the demo short) so the example is runnable on its own.

Node.js Negative tests: expiry, ownership and rate limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Mapping to real Fastify

This project Real Fastify
makeTokens @fastify/jwt (app.register(jwt, { secret }), reply.jwtSign, request.jwtVerify)
limitLogins @fastify/rate-limit with a route-level config.rateLimit and a Redis store
parse... and manual checks schema: { body: ... } on each route
setErrorHandler the same API, plus request.log.error for 5xx
authenticate a decorator used in onRequest hooks of a scoped plugin
hashPassword argon2 or bcrypt package (or node:crypto scrypt as shown)

Hardening ideas

  1. Short-lived access tokens plus refresh tokens kept in a table so they can be revoked.
  2. An account lockout or exponential delay after repeated failures for one email, not only per client.
  3. Email verification and password reset flows (single-use, expiring tokens).
  4. Security headers and CORS from Security Headers, CORS and Rate Limiting.
  5. Audit logging of logins, with passwords redacted (Logging with Pino).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do unknown email and wrong password return the same login message?

    Different messages (or timings) would let an attacker enumerate registered emails.
  2. 2. A user asks to delete another user's bookmark. Which response does this API give?

    Returning 404 avoids confirming that the id belongs to someone else.
  3. 3. Why does the API reject javascript: bookmark URLs?

    Only http and https are safe to render as links; other schemes can run scripts or leak data.
  4. 4. What makes the token expiry and rate-limit tests fast and reliable?

    When time is a parameter, tests move it instantly and the behavior stays deterministic.

Summary

  • A secure API layers hashed passwords, signed expiring tokens, an authentication hook, per-record ownership checks and a login rate limit.
  • Keep failure responses uniform (same message, 404 for foreign records) and never return secrets such as hashes.
  • Validate URLs and restrict schemes; bound string lengths.
  • Test the negative paths with an injected clock: expiry, tampering, ownership and throttling.
  • In real projects replace the hand-written parts with @fastify/jwt, @fastify/rate-limit, schemas and a maintained password library.

Next: Practice: Exercises and Interview Questions