Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 133 ยท Projects

Project: Blog and Social API with Auth

Build a blog and social API in Node.js with node:sqlite. Registration with scrypt, JWT login, posts, follows, a personal feed and cursor pagination, tested end to end with fetch.

Almost every product has the same skeleton: people create accounts, publish things, follow each other and read a feed. A blog with followers, a microblog, a recipe site and a developer forum differ in details, but the API behind them looks alike. Building this skeleton once teaches the parts that matter in real back ends: password storage, token authentication, authorization (who may edit what), relational queries and pagination that stays correct while new posts arrive.

You will build a small REST API with these endpoints:

Method and path Auth What it does
POST /register no create an account
POST /login no check the password, return a JWT
POST /posts yes publish a post
GET /posts?limit=&cursor= no public timeline, newest first, paginated
PATCH /posts/:id, DELETE /posts/:id yes, owner only edit or remove your own post
PUT /users/:name/follow, DELETE ... yes follow and unfollow
GET /feed?limit=&cursor= yes posts from people you follow

Everything runs in the editor: the database is node:sqlite in memory (SQLite in Node), the server is node:http, and the tests are fetch calls. Frameworks such as Express would shorten the routing code, but the design (service layer, error classes, token checks) is the same with any of them; see Project Structure and the REST API project.

Stage 1: schema and the data layer

Three tables hold everything. follows has a composite primary key so that following twice is impossible by construction, and indexes support the two queries the API runs all day: "newest posts" and "posts by these authors".

A note on pagination. LIMIT 10 OFFSET 20 is easy but wrong for a live timeline: if three new posts appear while the reader is on page 2, page 3 repeats three posts they already saw, and deleted posts make rows go missing. Keyset (cursor) pagination asks for "the 10 posts older than the last one I saw". The cursor is the id of the last post. With ids that grow over time, WHERE id < :cursor ORDER BY id DESC LIMIT :n is stable and also fast, because it uses the primary key index.

Node.js Schema, follows and keyset pagination

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.

The new post (id 8) was added between page 1 and page 2, and page 2 still started exactly where page 1 ended. With OFFSET it would have shifted everything by one. Fetching limit + 1 rows is a cheap way to know if there is a next page without a separate COUNT query.

Stage 2: passwords and tokens

Two rules govern accounts. Never store a password; store a salted, slow hash of it, so a database leak does not reveal passwords. Node's built-in scrypt does this (Password Hashing). And never tell an attacker which part of a login was wrong: "invalid name or password" for both cases. The login handler below also runs a hash for an unknown user, so the response time does not reveal whether the name exists.

After login the server returns a JSON Web Token (JWT): a signed statement "this is user 7, valid until 15:30". The server needs no session table to check it; it only verifies the signature with a secret key and the expiry (JWTs in depth). We build HS256 tokens by hand with node:crypto here. In production use a maintained library (jose) and keep the secret outside the code.

Node.js scrypt passwords and HS256 tokens

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.

The signature covers header and payload, so changing even one character of the payload invalidates it. Note that the payload is only encoded, not encrypted: anyone can read it, so put no secrets in a token. Keep the lifetime short; revoking a single JWT before it expires needs extra machinery (see refresh tokens in the lesson linked above).

Stage 3: the service layer and the HTTP API

Now we put the rules in one Blog class and keep HTTP thin. The class throws HttpError(status, message) for everything the client did wrong; the server catches it and writes the status. Anything else is a bug, so the server answers 500 and does not leak details.

Authorization deserves its own look. Authentication answers "who are you?" (the token). Authorization answers "may you do this?". Editing a post needs both: the token identifies the user, and post.author_id === user.id decides. A very common mistake is to check only the first. Posts here are public, so the API answers 403 Forbidden for a post that exists but is not yours, and 404 Not Found for one that does not exist. (For private resources, answer 404 in both cases so you do not reveal what exists.)

Node.js The complete blog API, exercised with fetch

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.

Read through the output top to bottom: that is the whole API contract in one screen. Notice the status codes: 201 for created things, 204 for success without a body, 400 for invalid input, 401 when you are not signed in or the token is bad, 403 when you are signed in but it is not yours, 404 for a missing resource and 409 for a conflict such as a taken name. Choosing the right status is what lets a client program react correctly (REST API Design).

Case-insensitive names matter. We declared the column COLLATE NOCASE, which is why registering ANA after ana returns 409. Without it you would have two accounts that look identical, which is a classic impersonation trick.

Hardening and next steps

  • Rate limit /login and /register per IP and per name to slow password guessing (Rate Limiting).
  • Validate with a schema library or hand-written checks, as the Blog class does, and always cap sizes.
  • Escape on output. The API stores text as given. Any website that shows posts must escape them when rendering HTML, or the post body becomes a cross-site scripting hole (Web Security).
  • Secrets. SECRET here is random on every start, so tokens die at a restart. Load a stable key from the environment (Secrets and Config).
  • Real database. SQLite is great up to a point; for several servers use PostgreSQL or MySQL. The service-layer structure lets you swap storage without touching the routes.
  • Extra features to practise on: likes with a unique (user, post) row, replies using a parent_id column, a GET /users/:name profile with follower counts using GROUP BY, and refresh tokens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is keyset (cursor) pagination better than OFFSET for a live timeline?

    OFFSET counts rows from the top, so anything inserted at the top moves every later page. A cursor says "older than this id", which is stable and index-friendly.
  2. 2. Why does the login handler hash a dummy password when the user does not exist?

    If unknown names answered instantly, an attacker could discover which names are registered by timing the responses. Doing the same work in both cases hides it.
  3. 3. A signed-in user tries to edit somebody else's post. Which status code is the best answer?

    401 means "who are you?" (missing or bad credentials). The user is known, but not allowed to change this post, which is 403.
  4. 4. Why can a JWT payload not hold secrets such as a password?

    The signature proves nobody changed the token, but it does not hide the content. Use short lifetimes and keep sensitive data on the server.
  5. 5. What does the composite primary key on the follows table (follower_id, followee_id) prevent?

    Each pair can exist only once, so a duplicate follow is rejected by the database itself, however many requests arrive at the same time.

Summary

  • A social API is users, posts and follows plus authentication, authorization and a feed query; keep the rules in one service class and the HTTP code thin.
  • Store scrypt hashes with a random salt, give the same answer for wrong names and wrong passwords, and sign short-lived tokens.
  • Authentication says who you are; authorization checks that you may touch this resource (403), and missing credentials are 401.
  • Use keyset pagination (WHERE id < cursor ORDER BY id DESC LIMIT n + 1) for feeds that change while people read.
  • Let the database enforce uniqueness (primary keys, UNIQUE, CHECK) instead of trusting application checks alone.

Next: Project: Payment Integration with Webhooks