Implementing Member Registration and Login in a Node.js Application
In modern web applications, user registration and authentication are fundamental functionalities. In this article, we'll go over how to implement member registration and login using a simple Node.js Express API. We'll be focusing on creating secure user accounts and handling authentication using JWT (JSON Web Token).
- Member Registration (POST /register) When a new user registers for your platform, the registration route is responsible for securely creating a new user record in the database. This involves capturing the user's details (such as email and password) and saving them after hashing the password for security purposes.
// Member Registration: POST /register
app.post('/register', async (req, res, next) => {
try {
let { email, password } = req.body;
// Create new member with email and password
let member = await Member.create({ email, password });
// Return the new member's ID and email
res.status(201).json({ id: member.id, email: member.email });
} catch (error) {
// Handle errors and pass to error middleware
next(error);
}
});
How It Works:
Request Body: The API expects an email and password in the request body.
Member Creation: The Member.create() function creates a new user in the database with the provided email and password.
Response: Upon successful registration, the response returns the new member's id and email with an HTTP status code of 201 (Created).
This route ensures that user data is securely saved and password hashing is implemented behind the scenes (not shown here, but typically done using libraries like bcryptjs).
- Member Login (POST /login) The login route allows an existing user to authenticate by providing their email and password. After validating the credentials, a JWT token is generated and returned to the user, which they can use to authenticate subsequent requests.
Code Breakdown:
// Member Login: POST /login
app.post('/login', async (req, res, next) => {
try {
let { email, password } = req.body;
// Check if email and password are provided
if (!email) throw ({ name: "Custom", message: "Email is required" });
if (!password) throw ({ name: "Custom", message: "Password is required" });
// Find the member by email
let member = await Member.findOne({ where: { email } });
// Validate if the member exists and the password is correct
if (!member || !comparePassword(password, member.password)) throw { name: "InvalidUser" };
// Generate JWT token for the authenticated user
res.status(200).json({ access_token: signToken({ id: member.id }) });
} catch (error) {
// Handle errors and pass to error middleware
next(error);
}
});
How It Works:
Request Body: The API expects the email and password in the request body.
Validation:
The code checks whether both email and password fields are present in the request.
It looks up the user in the database using the provided email. If no user is found or the password does not match, an error is thrown.
Password Comparison: The comparePassword() function (typically using bcryptjs) checks whether the provided password matches the hashed password stored in the database.
JWT Token Generation: If the credentials are valid, the signToken() function generates a JWT with the user's id as the payload. This token is sent back to the client in the response, and it can be used for subsequent authenticated requests.
Top comments (0)