title: express restAPI, how to properly validate requests and respond invalid requests?
body: <p><strong>My Environments:</strong></p>
  <p>Backend: Express Server connected to Postgres.
  Client: React hosted on a seperate server.</p>
  <p><strong>My example, I have a POST/signup endpoint on my express server that takes the following:</strong></p>
  <ol>
  <li>Username</li>
  <li>Email</li>
  <li>Password</li>
  </ol>
  <p><strong>Correct me if I'm wrong, the backend will need to verify the following validation:</strong></p>
  <ol>
  <li>check req.body that username, email and password are all present, otherwise respond:</li>
  </ol>
  <pre class="lang-js prettyprint-override"><code>res.status(400).send({ msg: &quot;Please pass
      username/email/password.&quot; });
  </code></pre>
  <ol start="2">
  <li>check if username, email are already in the database</li>
  </ol>
  <pre class="lang-js prettyprint-override"><code>SELECT * FROM accounts WHERE username = 'bee' OR email = 'bee@gmail.com';
  
  /*
  if exists, res.status(400).send({ msg: &quot;Username/Email already exists&quot; });
  else res.status(200).json({message: &quot;successfully signed up&quot;})
  */
  </code></pre>
  <ol start="3">
  <li>*** Do I need to add an additional format validation? i.e unacceptable characters for username, before I carry on inserting it into database.</li>
  </ol>
  <p>I ponder on this because I can imagine client-side may help with these tedious validation with formik/yup etc. But should i worry about the few people who make direct communication to my API without using my client application? Unless CORs help fix this problem?</p>
  <ol start="4">
  <li>*** How should i handle errors in general. Do i handle backend db/express request error via try...catch blocks to return    <code>res.status(400).json({message: &quot;server error&quot;});</code></li>
  </ol>
  <hr />
  <p>And one final thing, on step 2. Can I technically skip verifying whether username/email already exists and immediately insert the data anyways because postgreSQL will notify me if any unique values/constraints are affected... I can take postgreSQL error and transfer that to the client side? - if this is the way, I also have no idea how to do that.</p>
  <p><strong>Don't know if this matters:</strong></p>
  <p>I should note that, my express server is NOT also serving webpages. this express server is only a restAPI to provide some authentication logic/with sessions to use my DB for my client-side.</p>
  <p>I know its a lot of questions. if you have a way better strategy/resource, I would love to hear it. Or if there any any good libraries to help with development i would love know about it. Thank you.</p>