Skip to content

authToken.js : Cannot set headers after they are sent to the client #1

@great-park

Description

@great-park

If I send request without access-token, then server crash with "Cannot set headers after they are sent to the client" error.
I think that's because the application set header twice when we send request without access-token.
So, it can be solved by appliying if-else statement like below code

const authToken = async (req, res, next) => {
  const token = req.header("x-auth-token");

  // If token not found, send error message
  if (!token) {
    res.status(401).json({
      errors: [
        {
          msg: "Token not found",
        },
      ],
    });
  } else {
    // Authenticate token
    try {
      const user = await jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
      req.user = user.email;
      next();
    } catch (error) {
      res.status(403).json({
        errors: [
          {
            msg: "Invalid token",
          },
        ],
      });
    }
  }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions