Search code examples
node.jsmongodbjwtsendgrid

How to authenticate user email by sending a verification code using NodeJS?


I want to send a verification code to the registered Email ID of the user during signup. All the tutorials I found send a verification link using sendgrid API.

Is there any way I this could be done using a verification code instead?


Solution

  • you can do it by yourself.

    • in the user schema in the DB you need a boolean place for isAuthenticated and a string place for the auth code.
    • generate some code, if you're working with nodejs UUID package for NPM is a great package.
    • when a user is registered - save false by default, generate the code and:
      1. save it into the user in the DB
      2. send a mail to the user with a link to the endpoint on your server something like /:userid/:authcode
    • on the server - build this endpoint, select the user from the DB by the ID you got on the parameter, check if the code you got on the param is the same as the one saved in the user you just selected, and if so - update the user to true
    • last thing - on login - check if the auth is true, and if not - send a specific error so you can catch it on the client and display a nice detailed error message