Step 13

Import the createToken function to the auth.js:

const { createToken } = require("../util/token");

Next, update the route handler for /authenticate:

  router.post("/authenticate", async (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({
        message: "You must provide both username and password.",
      });
    }

    try {
      const user = await users.readOne(username);

      // Authentication!
      const isAuthenticated = await verifyPassword(password, user ? user.password : "");
      if (!isAuthenticated) {
        return res.status(403).json({
          message: "Wrong username or password!",
        });
      } else {
+       const token = createToken(user);
        return res.json({
          message: "Authentication successful!",
+         token: token,
-         data: user,
        });
      }
    } catch (err) {
      return res.status(err.status || 500).json({ message: err.message });
    }
  });

Save the file and try to authenticate a user again!

Notice the client receives a token after a successful authentication!