Send email to forget/reset password in Node js + Express + MySQL+ nodemailer; Through this tutorial you will learn how to send password reset link via email in node js + express js + MySQL database. And using this link how to reset/update password in node js + express + MySQL app.
Password Reset in AWS REST API -6- ...
if you createdlogin and registration application using node js + express + MySQL. Or you want to create a password reset and forget system with a password reset and password reset email link in your app. So in this tutorial you will learn how to send password reset link in an email to user and how user use sent password reset link to reset/update password in node js + express + MySQL application.
Node js Express + MySQL Forgotten/Reset Password Email Example
Let's follow the following steps to create forgotten or reset password email in node js express with MySQL:
- Step 1 – Install Node Express App JS
- Step 2 - Install required Node js modules
- Step 3 - Connect the Node Express JS application to the database
- Step 4 – Import Installed Modules in app.js
- Step 5 – Create Route to Forget and Reset Password
- Create email sending function with Gmail nodemailer setup
- Create password reset link with send to email
- Create password reset/update route
- Step 6 – Create visualizations
- Forgot password page
- Password reset/update page
- Step 7 – Run the development server
Step 1 – Install Node Express App JS
Run the following command in terminal to install the express js application:
express --view=ejs blog
so openblogconfigure with any text editor. And use the following command to enter yourblogapplication directories, so open your cmd and run the following command:
cdblog
Node js express js+mysql password reset email app structure looks like this:

Step 2 - Install required Node js modules
Install some necessary node js modules, then open your cmd again and run the following commands:
npm install express-flash --save npm install express-session --save npm install method-override --save npm install mysql --save npm install rand-token --save npm install body-parser --save npm install bcrypt npm instalar
Express-flash– Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
express session– Express-session is used to make a session like in PHP. In this node js mysql crud tutorial session is required as express requirement of express-flash.
method substitution– NPM is used to perform a DELETE and PUT method of an HTML form. In many web browsers, only the GET and POST methods are supported.
MySQL– Driver to connect node.js with MySQL.
rand-token- Generate random tokens of your choice of randomness.
body analyzer– Body-parser is Node. js body parsing middleware. That's itresponsible for parsing incoming request bodies in a middleware before handling them.
notes mailer– Nodemailer isa module for Node.js apps to allow sending email as easy as cake. The project started in 2010 when there was no sane option for sending email messages, today it is the most Node. js users resort to by default.
bcrypt– bcrypt isa popular and reliable method to salt and hash passwords. You learned how to use bcrypt's NodeJS library to salt and hash a password before storing it in a database. You also learned how to use the bcrypt compare function to compare a password with a hash, which is required for authentication.
If you want to send email from localhost or without ssl certificate, you can also run following command in your terminal:
npm config set strict-ssl false --globalset NODE_TLS_REJECT_UNAUTHORIZED=0
Recommended:-Node js express upload file/image example
Step 3 - Connect the Node Express JS application to the database
Before connecting the database to your node js email verification application, create a table in your database using the following SQL query:
-- phpMyAdmin SQL Dump-- Version 5.0.2-- https://www.phpmyadmin.net/---- Host: 127.0.0.1-- Generation Time: Sep 11, 2021 at 2:49pm-- Server Version : 10.4.14-MariaDB-- PHP Version: 7.4.9SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";START TRANSACTION;SET time_zone = "+00:00";---- Database: `my-node`---- -- ------------------------------------------------ -- -------- Table structure for the `users` table--CREATE TABLE `users` ( `id` int(11) NOT NULL, `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL , `email` varchar( 50) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf 8mb4_unicode_ci;-- - - Indexes for evicted tables ------ Indexes for table `users`--ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `email` (`email`);--- - AUTO_INCREMENT for dumped tables-- ---- AUTO_INCREMENT for `users` table--ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;COMMIT;
Next, visit the app's root directory and create a file name database.js. Then add the following code in your database.js file:
var mysql=require('mysql'); var connection=mysql.createConnection({ host:'localhost', user:'root', password:'', database:'my-node' });connection.connect(function(error){ if(!!error) { console.log(error); }else{ console.log('Conectado!:)'); } }); module.exports = conexão;
Note that this file is used to connect your node express js application to MySQL database.
Recommended:-Node js Express MySQL User Authentication Rest API Example
Step 4 – Import Installed Modules in app.js
Import the above installed node js modules into the app.js file; So, open your app.js file and import all the above packages installed inapp.jsfile.
then go toapp.jsfile and update the following code:
var createError = require('http-errors');var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require(' morgan');var flash = require('express-flash');var session = require('express-session');var bodyParser = require('body-parser');var indexRouter = require('./routes/ index');var usersRouter = require('./routes/users');var app = express();// view engine setupapp.set('views', path.join(__dirname, 'views'));app .set('view engine', 'ejs');app.use(logger('dev'));app.use(express.json());app.use(express.urlencoded({ extendido: false }) );app.use(cookieParser());app.use(express.static(path.join(__dirname, 'public')));app.use(session({ secret: '123458cat', resave: false, saveUninitialized : true, cookie: { maxAge: 60000 }}))app.use(flash());//app.use('/', indexRouter);app.use('/', usersRouter);// catch 404 e encaminhar para error handlerapp.use(function(req, res, next) { next(createError(404));});// error handlerapp.use(function(err, req, res, next) { // definir locais , apenas fornecendo erro no desenvolvimento res.locals.message = err.message; res.locals.error = req.app.get('env') === 'desenvolvimento' ? erro: {}; // renderiza a página de erro res.status(err.status || 500); res.render('erro'); });app.listen(4000, function () { console.log('O aplicativo do nó está sendo executado na porta 4000');});module.exports = app;
Recommended:-Node js get and send data from example Ajax request
Step 5 – Create Route to Forget and Reset Password
Create forgetting routes and password reset with email link sending; then visit routes directory and open index.js route file and create routes as shown below:
Create email sending function with Gmail nodemailer setup
//send email function sendEmail(email, token) { var email = email; var token = token; var mail = nodemailer.createTransport({ service: 'gmail', auth: { user: '', // Your email pass id: '' // Your password } }); var mailOptions = { from: '[email protected]', to: email, subject: 'Password Reset Link - Tutsmake.com', html: 'You requested a password reset, use thislinkto reset your password
' }; mail.sendMail(mailOptions, function(error, info) { if (error) { console.log(1) } else { console.log(0) } });}
now open the linkhttps://myaccount.google.com/lesssecureappsforAllow less secure apps: ON. It will send the email using Gmail account.
Create password reset link with send to email
/* send password reset link in email */router.post('/reset-password-email', function(req, res, next) { var email = req.body.email; //console.log(sendEmail (email , fullUrl)); connection.query('SELECT * FROM users WHERE email ="' + email + '"', function(err, result) { if (err) throw err; var type = '' var msg = '' console.log(result[0]); if (result[0].email.length > 0) { var token = randtoken.generate(20); var sent = sendEmail(email, token); if (sent ! = ' 0') { var data = { token: token } connection.query('UPDATE users SET ? WHERE email ="' + email + '"', data, function(err, result) { if(err) throw err }) type = 'success'; msg = 'Password reset link has been sent to your email address'; } else { type = 'error'; msg = 'Something went wrong. Please try again '; } } else { console.log('2'); type = 'error'; msg = 'Email is not registered with us'; } req.flash(type, msg); res.redirect('/ '); });})
Create password reset/update route
/* atualiza a senha para o banco de dados */router.post('/update-password', function(req, res, next) { var token = req.body.token; var password = req.body.password; connection.query( 'SELECT * FROM users WHERE token ="' + token + '"', function(err, result) { if (err) throw err; var type var msg if (result.length > 0) { var saltRounds = 10; / / var hash = bcrypt.hash(password, saltRounds); bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(password, salt, function(err, hash) { var data = { password: hash } connection .query('UPDATE users SET ? WHERE email ="' + resultado[0].email + '"', data, function(err, result) { if(err) throw err }); }); }); type = 'sucesso'; msg = 'Sua senha foi atualizada com sucesso'; } else { console.log('2'); type = 'sucesso'; msg = 'Link inválido; tente novamente'; } req.flash( tipo, msg); res.redirect('/'); });})
Full source code of users.js route:
var express = require('express');var router = express.Router();var connection = require('../database.js');var nodemailer = require('nodemailer');var bcrypt = require(' bcrypt');var randtoken = require('rand-token');//enviar emailfunction sendEmail(email, token) {var email = email;var token = token;var mail = nodemailer.createTransport({service: 'gmail' ,auth: {user: '', // Seu e-mail idpass: '' // Sua senha}});var mailOptions = {from: '[email protected]',to: email,subject: 'Password Reset Link - Tutsmake.com',html: 'You requested a password reset, use thislinkto reset your password
'};mail.sendMail(mailOptions, function(error, info) {if (error) {console.log(1)} else {console.log(0)}});}/* homepage */router.get ('/', function(req, res, next) {res.render('index', {title: 'Forgot Password Page'});});/* send password reset link in email * /router.post('/reset-password-email', function(req, res, next) {var email = req.body.email;/ /console.log(sendEmail(email, fullUrl));connection.query( 'SELECT * FROM users WHERE email ="' + email + '"', function(err, result) { if (err) throw err;var type = ''var msg = ''console.log(result[0]) ;if (result[0].email.length > 0) {var token = randtoken.generate(20);var sent = sendEmail(email, token );if (sent != '0') {var data = {token : token}connection.query('UPDATE users SET ? WHERE email ="' + email + '"', data, function(err, result) { if(err) throw err})type = 'success';msg = ' Password reset link has been sent to your email address';} else {type = 'error';msg = 'Something went wrong. Please try again';}} else {console.log(' 2');type = 'error';msg = 'Email is not registered with us';}req.flash(type, msg);res.redirect( '/');});})/* page from reset */router.get('/reset-password', function(req, res, next) {res.render('reset-password', {title: 'Reset password page',token: req.query. token});});/* update password to database */router.post('/update-password', function(req, res, next) {var token = req .body.token;var password = req.body.password;connection.query('SELECT * FROM users WHERE token ="' + token + '"', function(err, result) { if (err) throw err;var typevar msgif (result.length > 0 ) { var saltRounds = 10; // var hash = bcrypt.hash(password, saltRounds);bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(password, salt, function(err, hash) {var data = {password: hash}connection.query('UPDATE users SET ? WHERE email ="' + result[0].email + '"', data, function(err, result) { if(err) throw err});});});type = 'success';msg = ' Your password has been successfully updated';} else {console.log('2');type = 'success'; msg = 'Invalid link; try again';}req.flash(type, msg);res.redirect('/');});})module.exports = router;
Recommended:-Node JS Express Crud with Mysql example
Step 5 – Create visualizations
Create pages to forget password and reset/update password; then visit the application root directory and find the views directory.
Forgot password page
Then inside this directory create an index.ejs file. And add the following code in it:
<%= title %> <% if (messages.error) { %><%-messages. error %>
<% } %><% if (messages.success) { %><%-messages.success %>
<% } %><%= title %>
Password reset/update page
Then inside this directory create a reset-password.ejs file. And add the following code in it:
<%= title %> - tutsmake.com <% if (messages.error) { %>< %-messages.error %>
<% } %><% if (messages.success) { %><%-messages.success %>
< % } %><%= title %>
Step 7 – Run the development server
You can use the following command to run the development server:
// run the commandnpm below startafter run this command open your browser and click http://127.0.0.1:4000/
If you found any error, while sending email with Gmail SMTP; Then you can follow these two steps and solve it:
- You need to activate Gmail service to use it in third-party apps. In case you fail to do so, we may face this error. To resolve this error simply login to Gmail account and enable less secure apps using this linkhttps://myaccount.google.com/lesssecureapps
- self-signed certificate in the certificate chain.
- Run this command in termianl:
- npm config set strict-ssl false –globalset
- NODE_TLS_REJECT_UNAUTHORIZED=0
- Run this command in termianl:
Conclusion
Send forget/reset password in Node js + Express + MySQL+ nodemailer; Through this tutorial you learned how to send password reset link via email in node js + express js + MySQL database. And using this link how to reset/update password in node js + express + MySQL app.
Node js recommended tutorials
Recommended:-Node Js Google ReCaptcha v3 Example
Recommended:-Node.js express login example with MySQL
Recommended:-Node js Express + CRUD Rest Apis + MySQL Exemplo
Recommended:-Load image into MySQL database using Node js Express + Multer
Recommended:-Node JS Facebook Login Example
Recommended:-Node JS Resize image before upload using Multer Sharp Example
Recommended:-Node JS Google Authentication with passport example
Recommended:-Node js Express Get Client IP Address tutorial
Recommended:-Node js Upload CSV file to MySQL database
Recommended:-JS node dependent dropdown list example tutorial
Recommended:-Node js + MySQL Autocomplete search example
Recommended:-Node JS Google Places Autocomplete Address Example
Recommended:-Node.js Express Habilitar HTTPS