In this tutorial, we will learn how to create a SignUp and SignIn API using Node.js and Express.js. Node.js is a popular runtime environment for building server-side applications, while Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Step 1: Setting up the project
First, create a new directory for your project and navigate to it in your terminal. Then, initialize a new Node.js project by running the following command:
npm init -y
Next, install Express.js and a few other dependencies by running the following command:
npm install express body-parser cors bcrypt jsonwebtoken
Step 2: Create the server.js file
Create a new file named server.js in the root directory of your project. This file will be the main entry point for our application. Here’s an example of what the server.js file might look like:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
app.post('/signup', (req, res) => {
// Logic to handle user sign up
});
app.post('/signin', (req, res) => {
// Logic to handle user sign in
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 3: Implement the SignUp endpoint
In the /signup route handler, we will create a new user account and store the user’s credentials securely. Here’s an example of how you might implement the SignUp logic:
const users = [];
app.post('/signup', async (req, res) => {
try {
const { email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = { email, password: hashedPassword };
users.push(user);
res.status(201).send('User created successfully');
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
Step 4: Implement the SignIn endpoint
In the /signin route handler, we will verify the user’s credentials and generate a JSON Web Token (JWT) for authentication. Here’s an example of how you might implement the SignIn logic:
app.post('/signin', async (req, res) => {
try {
const { email, password } = req.body;
const user = users.find(user => user.email === email);
if (!user) {
return res.status(401).send('Invalid email or password');
}
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(401).send('Invalid email or password');
}
const token = jwt.sign({ email }, 'your_secret_key');
res.status(200).json({ token });
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
Step 5: Test the API endpoints
You can now start the server by running the server.js file using the following command:
node server.js
You can test the SignUp and SignIn endpoints using tools like Postman or cURL. Send a POST request to http://localhost:3000/signup with a JSON body containing the user’s email and password to create a new account. Then, send a POST request to http://localhost:3000/signin with the same credentials to log in and receive a JWT token.
Congratulations! You have successfully created a SignUp and SignIn API using Node.js and Express.js. You can continue to enhance this API by adding features like user authentication, error handling, and database integration. Happy coding!