In today's web development world, REST APIs have become a standard for enabling communication between different applications. Node.js, thanks to its robustness and flexibility, is one of the most widely used platforms for building efficient and scalable APIs. In this tutorial, we'll focus on building a REST API in Node.js that includes authentication using JSON Web Tokens (JWT), a secure method for transmitting information between parties as a JSON object.
Why use JWT for authentication?
Using JWTs for authentication and session management is popular because of their ability to be self-contained, meaning they contain all the necessary information about the user. Additionally, they are secure because they are digitally signed. This reduces the need to store information on the server, making them ideal for scalable APIs.
Setting Up Our Node.js Project
First, we'll create a new Node.js project using npm:
$ mkdir myapi && cd myapi
$ npm init -y
Next, we'll install the necessary libraries:
$ npm install express jsonwebtoken bcryptjs
These include Express, a popular Node.js framework; jsonwebtoken, for handling JWTs; and bcryptjs, to encrypt passwords.
Creating the Basic Server
We open our index.js
file and implement a basic server:
const express = require(express);
const app = express();
app.use(express.json());
app.listen(3000, () => console.log(Server running on port 3000));
This code starts a server on port 3000 and enables handling of JSON requests.
Handling Users and Security
We will add basic endpoints to register users and handle their authentication. We will create a simple handler for it:
// Database simulation
let users = [];
app.post(/register, async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.status(201).send(User successfully registered);
});
app.post(/login, async (req, res) => {
const { username, password } = req.body;
const user = users.find(user => user.username === username);
if (!user ||
)) {
return res.status(401).send(Incorrect credentials);
}
const token = jwt.sign({ username: user.username }, secretkey);
res.json({ token });
});
Securing our Routes with JWT
To protect our routes we will require a middleware function that validates the tokens:
const authenticateJWT = (req, res, next) => {
const token = req.header(Authorization);
if (!token) return res.sendStatus(403);
jwt.verify(token.split( )[1], secretkey, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};;
We can then use this feature on any routes we want to secure.
Putting it all together
You can see how these combined features make it possible to build robust applications. By using JWTs, we not only secure our routes with strong VPNs and ciphers, but we also improve the user experience by eliminating the constant need to log in.
More about developing with Mox here.