Project 3: A Blog API with Roles

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 9 min read · Updated

Who may do what

  1. Anyone may read published posts. Drafts are never shown.
  2. An author creates drafts and edits only the posts that they own.
  3. Only an admin can publish, or change any post.
  4. Any logged-in user may comment on a published post.

A blog sounds simple until you ask who may do what. Anyone may read a published post. A logged-in user may comment. An author may write and edit their own posts but not those of others. Only an admin may publish. That list of permissions is what makes this project a good test of your understanding of authorization, and it is a standard portfolio piece for a reason: the data is easy to understand, so the reviewer can concentrate on how you handled the rules.

What you will build

  • Public GET /api/posts that lists only published posts, with paging, a category filter and search.
  • GET /api/posts/:slug that shows one published post.
  • Authors and admins create, edit and delete posts. Authors only their own.
  • POST /api/posts/:id/publish for admins only.
  • Logged-in users add comments to published posts.
  • GET /api/categories with the number of posts in each.

Design decisions before any code

Three roles are used: reader, author and admin. A post has a title, a body, a slug made from the title, a category, a status of draft or published, and the id of its author. New posts always start as drafts, so an author can never publish by mistake or on purpose. Publishing is a separate action with its own route and its own role check.

Drafts must not leak. The public list and the single-post route filter on status === 'published'. A draft asked for by slug answers 404, not 403, because 403 would confirm that the draft exists.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken.
  3. Copy p-kit.js, p03-blog.js and p03.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest, then run node --test p03.test.js.

The code uses the helpers from p-kit.js: requireAuth for logged-in routes and requireRole for role checks. Notice that the ownership check for editing and deleting is written inside the route, because it needs the post that it loads.

// Project 3: a blog API. Posts, categories, comments, and roles (reader, author, admin).
import express from 'express';
import { AppError, requireAuth, requireRole, errorHandler, notFoundHandler } from './p-kit.js';

const slugify = (text) => text.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');

export function createApp() {
  const app = express();
  app.use(express.json());
  const auth = requireAuth();
  const categories = new Map();
  const posts = new Map();
  const comments = [];

  // Public: only published posts, with paging, category filter and search.
  app.get('/api/posts', (req, res) => {
    const { category, q } = req.query;
    let list = [...posts.values()].filter((p) => p.status === 'published');
    if (category) list = list.filter((p) => p.category === category);
    if (q) list = list.filter((p) => (p.title + p.body).toLowerCase().includes(String(q).toLowerCase()));
    res.json(list.sort((a, b) => b.id - a.id).map(({ body, ...summary }) => summary));
  });

  app.get('/api/posts/:slug', (req, res) => {
    const post = [...posts.values()].find((p) => p.slug === req.params.slug && p.status === 'published');
    if (!post) throw new AppError('Post not found', 404);
    res.json({ ...post, comments: comments.filter((c) => c.postId === post.id) });
  });

  // Authors and admins can write.
  app.post('/api/posts', auth, requireRole('author', 'admin'), (req, res) => {
    const { title, body, category = 'general' } = req.body ?? {};
    if (typeof title !== 'string' || title.trim().length < 3 || typeof body !== 'string' || !body.trim()) throw new AppError('title (3+ letters) and body are required', 422);
    categories.set(category, (categories.get(category) ?? 0) + 1);
    const post = { id: posts.size + 1, slug: slugify(title), title: title.trim(), body, category, authorId: req.user.id, status: 'draft' };
    posts.set(post.id, post);
    res.status(201).json(post);
  });

  // An author may change their own posts. An admin may change any post and publish.
  const own = (req) => {
    const post = posts.get(Number(req.params.id));
    if (!post) throw new AppError('Post not found', 404);
    if (post.authorId !== req.user.id && req.user.role !== 'admin') throw new AppError('This is not your post', 403);
    return post;
  };

  app.patch('/api/posts/:id', auth, requireRole('author', 'admin'), (req, res) => {
    const post = own(req);
    const { title, body } = req.body ?? {};
    if (typeof title === 'string') { post.title = title.trim(); post.slug = slugify(title); }
    if (typeof body === 'string') post.body = body;
    res.json(post);
  });

  app.post('/api/posts/:id/publish', auth, requireRole('admin'), (req, res) => {
    const post = posts.get(Number(req.params.id));
    if (!post) throw new AppError('Post not found', 404);
    post.status = 'published';
    res.json(post);
  });

  app.delete('/api/posts/:id', auth, requireRole('author', 'admin'), (req, res) => {
    posts.delete(own(req).id);
    res.status(204).end();
  });

  // Any logged-in user can comment on a published post.
  app.post('/api/posts/:id/comments', auth, (req, res) => {
    const post = posts.get(Number(req.params.id));
    if (!post || post.status !== 'published') throw new AppError('Post not found', 404);
    const text = String(req.body?.text ?? '').trim();
    if (!text || text.length > 1000) throw new AppError('Comment must be 1 to 1000 characters', 422);
    const comment = { id: comments.length + 1, postId: post.id, userId: req.user.id, author: req.user.name, text };
    comments.push(comment);
    res.status(201).json(comment);
  });

  app.get('/api/categories', (req, res) => res.json([...categories].map(([name, posts]) => ({ name, posts }))));

  app.use(notFoundHandler, errorHandler);
  return app;
}

The test plays the three roles one after another.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './p03-blog.js';
import { signToken } from './p-kit.js';

const as = (id, role, name = `user${id}`) => ({ Authorization: `Bearer ${signToken({ id, role, name })}` });

test('project 3: blog roles, publishing and comments', async () => {
  const app = createApp();
  const author = as(2, 'author', 'Meera');
  const admin = as(1, 'admin');
  const reader = as(3, 'reader', 'Ravi');

  assert.equal((await request(app).post('/api/posts').send({ title: 'Hi there', body: 'x' })).status, 401);
  assert.equal((await request(app).post('/api/posts').set(reader).send({ title: 'Hi there', body: 'x' })).status, 403);

  const created = await request(app).post('/api/posts').set(author).send({ title: 'Learn Express Fast!', body: 'Routes and middleware', category: 'node' });
  assert.equal(created.body.slug, 'learn-express-fast');
  assert.equal(created.body.status, 'draft');

  assert.equal((await request(app).get('/api/posts')).body.length, 0);                         // drafts are hidden
  assert.equal((await request(app).post('/api/posts/1/publish').set(author)).status, 403);     // authors cannot publish
  assert.equal((await request(app).post('/api/posts/1/publish').set(admin)).status, 200);

  assert.equal((await request(app).get('/api/posts?category=node')).body[0].title, 'Learn Express Fast!');
  assert.equal((await request(app).get('/api/posts?q=middleware')).body.length, 1);
  assert.equal((await request(app).get('/api/posts/learn-express-fast')).status, 200);

  assert.equal((await request(app).post('/api/posts/1/comments').set(reader).send({ text: 'Great post' })).status, 201);
  assert.equal((await request(app).post('/api/posts/1/comments').send({ text: 'anon' })).status, 401);
  const detail = await request(app).get('/api/posts/learn-express-fast');
  assert.equal(detail.body.comments[0].author, 'Ravi');

  // Another author cannot edit or delete Meera's post. The admin can.
  assert.equal((await request(app).patch('/api/posts/1').set(as(9, 'author')).send({ title: 'Hijack' })).status, 403);
  assert.equal((await request(app).delete('/api/posts/1').set(admin)).status, 204);
  assert.deepEqual((await request(app).get('/api/categories')).body, [{ name: 'node', posts: 1 }]);
});

Rules worth understanding

Role check first, ownership second. requireRole('author', 'admin') decides whether the kind of user may use the route at all. Then the route loads the post and checks post.authorId === req.user.id, unless the user is an admin. Both checks are needed. A role says *what kind of user*, ownership says *whose data*. Forgetting the second check is one of the most common real-world access control bugs, because every author could then edit every post.

Slugs. A slug is the readable part of a URL, such as my-first-post. It is made from the title in lower case, with spaces turned into hyphens and strange characters removed, and it must be unique. Good slugs help both people and search engines.

Comments belong to published posts only. A comment on a draft or a missing post returns 404. The text is trimmed and limited to 1000 characters.

Counting categories. The categories route returns each name with its number of posts. With a database this becomes a $group stage of an aggregation, as in lesson 25.

Security and honesty notes

Comments contain text from strangers. The API stores them as they are, and the front end must escape them when drawing the page, as lesson 30 explains. If you allow HTML in posts, clean it with a library such as DOMPurify before you save or show it.

Never take the author id from the request body. The code uses req.user.id from the verified token.

Extend it

Your task

  1. Add GET /api/posts/mine for an author to see their drafts.
  2. Add tags with a filter, and an index on them in MongoDB.
  3. Add a moderation flag to comments and an admin route to hide them.

How to check it worked

  • An author cannot edit another author's post.
  • A draft returns 404 to the public.
  • Only an admin can publish.

On your resume. "Designed role-based access control for a blog API, with ownership checks, draft and publish workflow and automated tests of every permission" shows that you understand authorization. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

Why return 404 for another author's draft?

A 403 would confirm that the draft exists. A 404 tells a stranger nothing.

What is a slug?

A readable, unique text in the URL, made from the title, such as my-first-post. It is better for people and for search engines than a number.

Where should roles be stored?

In your database, on the user. They are copied into the token by the server, and never read from the request body.

Practise with interview questions