Building a User Authentication API with Email Verification and Image Upload using Node.js

Building a User Authentication API with Email Verification and Image Upload using Node.js

Table of contents

No heading

No headings in the article.

Introduction

User authentication is an essential part of modern web applications. In this guide, we'll build a user authentication API using Node.js with email verification and image upload features. We'll use Express.js, MongoDB, and Multer for image handling.

Prerequisites

Before starting, ensure you have the following installed:

  • Node.js

  • MongoDB (local or cloud-based)

  • Nodemailer (for email verification)

  • Multer (for image uploads)

Setting Up the Project

  1. Initialize the project

mkdir auth-api && cd auth-api

npm init -y

  1. Install required dependencies

npm install express mongoose dotenv bcryptjs jsonwebtoken multer nodemailer cors body-parser

Creating the Server

Create an index.js file and set up an Express server.

const express = require("express");

const mongoose = require("mongoose");

const dotenv = require("dotenv");

const cors = require("cors");

dotenv.config();

const app = express();

app.use(express.json());

app.use(cors());

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })

.then(() => console.log("MongoDB Connected"))

.catch(err => console.error(err));

app.listen(5000, () => console.log("Server running on port 5000"));

User Model

Create a models/User.js file to define the user schema.

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({

name: String,

email: { type: String, unique: true },

password: String,

verified: { type: Boolean, default: false },

image: String

});

module.exports = mongoose.model("User", UserSchema);

User Authentication Routes

Create an routes/auth.js file.

Register User with Email Verification

const express = require("express");

const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");

const User = require("../models/User");

const nodemailer = require("nodemailer");

const router = express.Router();

// Email transporter setup

const transporter = nodemailer.createTransport({

service: "gmail",

auth: { user: process.env.EMAIL, pass: process.env.EMAIL_PASS }

});

router.post("/register", async (req, res) => {

try {

const { name, email, password } = req.body;

const hashedPassword = await bcrypt.hash(password, 10);

const user = new User({ name, email, password: hashedPassword });

await user.save();

const token = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: "1d" });

const verificationUrl = http://localhost:5000/auth/verify/${token};

await transporter.sendMail({

to: email,

subject: "Verify Your Email",

text: Click here to verify your email: ${verificationUrl}

});

res.json({ message: "Registration successful. Please check your email for verification link." });

} catch (err) {

res.status(500).json({ error: err.message });

}

});

Email Verification

router.get("/verify/:token", async (req, res) => {

try {

const { token } = req.params;

const decoded = jwt.verify(token, process.env.JWT_SECRET);

await User.updateOne({ email: decoded.email }, { verified: true });

res.send("Email Verified Successfully!");

} catch (err) {

res.status(400).send("Invalid or Expired Token");

}

});

Image Upload with Multer

Create a middlewares/upload.js file to configure Multer.

const multer = require("multer");

const storage = multer.diskStorage({

destination: (req, file, cb) => cb(null, "uploads/"),

filename: (req, file, cb) => cb(null, Date.now() + "-" + file.originalname)

});

module.exports = multer({ storage });

Profile Image Upload Route

const upload = require("../middlewares/upload");

router.post("/upload", upload.single("image"), async (req, res) => {

try {

const user = await User.findById(req.user.id);

user.image = req.file.path;

await user.save();

res.json({ message: "Image uploaded successfully", image: req.file.path });

} catch (err) {

res.status(500).json({ error: err.message });

}

});

Running the Application

  1. Create a .env file and add:

MONGO_URI=your_mongodb_connection_string

JWT_SECRET=your_jwt_secret

EMAIL=your_email@gmail.com

EMAIL_PASS=your_email_password

  1. Start the server:

node index.js

With the steps above, you can successfully build a user authentication API with Email verification and image upload using NodeJs.