Ria Choi
← Portfolio

Express Book Reviews

An IBM course project that uses Express to separate public book searches from review editing, with JWT and session middleware for signed-in users.

Express Book Reviews

Express Book Reviews (IBM Course Project)

I built this REST API for a bookshop with Node.js and Express as part of the IBM course. Anyone can browse books, and registered users can log in and add or delete their own reviews. Login uses JWT and sessions to protect those routes.

Public routes with async/await and Promises

Browsing routes let anyone list books or search by ISBN, author, or title. I wrote them with async/await and Promises to practice asynchronous patterns:

JavaScript
public_users.get('/author/:author', async (req, res) => {
    try {
        const author = req.params.author;

        const fetchBooksByAuthor = async () => {
            let filteredBooks = [];
            for (let isbn in books) {
                if (books[isbn].author === author) {
                    filteredBooks.push(books[isbn]);
                }
            }
            return filteredBooks;
        };

        const booksByAuthor = await fetchBooksByAuthor();

        if (booksByAuthor.length > 0) {
            return res.status(200).json(booksByAuthor);
        } else {
            return res.status(404).json({ message: "No books found for this author" });
        }
    } catch (error) {
        return res.status(500).json({ message: "Error retrieving book details" });
    }
});

The ISBN route uses a Promise with .then() and .catch() instead:

JavaScript
new Promise((resolve, reject) => {
    let book = books[isbn];
    if (book) resolve(book);
    else reject("Book not found");
})
    .then((book) => res.status(200).json(book))
    .catch((error) => res.status(404).json({ message: error }));

Registration

Registration validates the input, rejects duplicate usernames with a 409, and stores the new user:

JavaScript
let existingUser = users.find((user) => user.username === username);

if (existingUser) {
    return res.status(409).json({ message: "User already exists" });
}

users.push({ username, password });

Login with JWT and sessions

On login, the server checks the credentials, creates a JWT that expires in one hour, and saves it in the session:

PHP
let accessToken = jwt.sign(
    { data: password },
    "access",
    { expiresIn: 60 * 60 }
);

req.session.authorization = { accessToken, username };

Protecting routes with middleware

Any route under /customer/auth/* goes through middleware that reads the token from the session and verifies it. If it's missing or invalid, the request is rejected with a 403:

JavaScript
app.use("/customer/auth/*", function auth(req, res, next) {
    if (req.session.authorization) {
        let token = req.session.authorization['accessToken'];

        jwt.verify(token, 'access', (err, user) => {
            if (!err) {
                req.user = user;
                next();
            } else {
                return res.status(403).json({ message: "User not authenticated" });
            }
        });
    } else {
        return res.status(403).json({ message: "User not logged in" });
    }
});

Adding and deleting reviews

Reviews are stored per user, so each user can only add, update, or delete their own review:

SQL
books[isbn].reviews[username] = review;      // add or update
delete books[isbn].reviews[username];        // delete

What I learned

  • Building a REST API with Express routers and proper HTTP status codes
  • Using Promises and async/await for asynchronous code
  • Implementing JWT authentication with express-session and custom middleware
  • Protecting routes so only logged-in users can change their own data

Things to improve

Since this is a course project, a few things would need changing for real use:

  • Passwords are stored in plain text, so they should be hashed with bcrypt
  • The JWT payload contains the password ({ data: password }), which should be the username or user ID instead
  • The JWT secret ("access") and session secret are hardcoded and should move to environment variables
  • Users and books live in memory, so they reset when the server restarts