EShopExplore

Location:HOME > E-commerce > content

E-commerce

Sending Password Reset and OTP Links Using Node.js: A Step-by-Step Guide

June 02, 2025E-commerce3424
Sending Password Reset and OTP Links Using Node.js: A Step-by-Step Gui

Sending Password Reset and OTP Links Using Node.js: A Step-by-Step Guide

In today's digital age, user authentication and verification processes are paramount. Two common methods for enhancing security and improving user experience are sending password reset links and one-time password (OTP) links via email and SMS. This article will provide a comprehensive guide on how to implement these features in a Node.js application using relevant packages such as nodemailer for email and SMS APIs for SMS.

Prerequisites

To follow this guide, ensure that you have the following:

Node.js installed on your system. An SMTP server configured for email sending (e.g., Gmail). An SMS API provider and credentials. A database to store user tokens and other necessary data.

Sending a Password Reset Link with nodemailer

Step 1: Install the necessary package

Begin by installing the nodemailer package using npm:

npm install nodemailer

Step 2: Import and configure the package

Import the nodemailer package and set up the transporter object for sending emails.

const nodemailer  require('nodemailer');let transporter  ({    host: '',    port: 465,    secure: true,    auth: {        user: 'your-email@',        pass: 'your-email-password'    }});

Step 3: Set up the email options

Create an emailOptions object with the recipient's information, subject, and the reset link.

let emailOptions  {    from: 'noreply@',    to: 'user@',    subject: 'Password Reset',    html: `pClick here to reset your password./p`};

Step 4: Send the email

Use the sendMail method to send the email.

async function sendEmail() {    try {        let info  await (emailOptions);        console.log('Email sent: '   );    } catch (error) {        console.log('Error sending email: '   error);    }}sendEmail();

Step 5: Store and verify the token

Generate a unique token for the password reset link and associate it with the user's account in your database. This token is used to verify the reset link when the user clicks on it.

Example token generation:

const jwt  require('jsonwebtoken');const jwtToken  ({ userId: 'user123' }, 'your-private-key', { expiresIn: '15m' });

Generating and Sending OTPs

Method 1: Email OTP

To generate and send an OTP via email, you can use the following steps:

Step 1: Define the OTP generation function

function generateOTP() {    var digits  '0123456789';    var OTP  '';    for (let i  0; i  6; i  ) {        OTP   digits[Math.floor(Math.random() * 10)];    }    return OTP;}const otp  generateOTP();

Step 2: Update user OTP in the database

const updateQuery  `update registration set otp_msg${otp} where email${userEmail}`;

Step 3: Send the email

const mailOptions  {    from: 'noreply@',    to: `${userEmail}`,    subject: 'OTP Code',    html: `

Your OTP is: ${otp}

`};async function sendEmail() { try { let info await (mailOptions); console.log('Email sent: ' ); } catch (error) { console.log('Error sending email: ' error); }}sendEmail();

Method 2: SMS OTP

To send an OTP via SMS, you need to use an API provider. Here is a basic example using a fictional SMS API provider:

Note: Replace the placeholders with your actual API credentials and SMS gateway provider.

const axios  require('axios');const API_KEY  'your-api-key';const SMS_ENDPOINT  '';let smsOptions  {    phone: `${userPhone}`,    message: `Your OTP is: ${otp}`};async function sendSMS() {    try {        await (SMS_ENDPOINT, smsOptions, {            headers: {                'Authorization': `Bearer ${API_KEY}`            }        });        console.log('SMS sent successfully');    } catch (error) {        console.log('Error sending SMS: '   error);    }}sendSMS();

Conclusion

By following the steps outlined in this guide, you can successfully implement password reset and OTP functionality in your Node.js application. Ensure you handle security best practices such as token validation and secure storage to prevent unauthorized access.

For more detailed implementation and customization, refer to the documentation of the libraries and API providers you use.