MOX
Products
Learn about our additional services
Resources & Elements
Return

MOXAndrés Villalobos
09-09-2025

Node.js + Express Tutorial: Implementing JWT Authentication in REST APIs

In today's world of web development, applications require a robust authentication system that allows for secure management of user access. In this context, implementing a system based on JSON Web Tokens (JWT) has become a popular approach due to its simplicity and effectiveness. This tutorial focuses on teaching you how to create a REST API using Node.js and Express, implementing JWT authentication.

What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, self-contained format for transmitting information between parties as a JSON object. This information can be verified and digitally signed, making it ideal for authentication and secure data exchange.

Prerequisites

Before you begin, make sure you have Node.js installed on your machine. Additionally, you'll need some basic development tools:

  • Node.js: To run JavaScript on the server.
  • Express: A framework that makes it easy to build web applications.
  • Postman or Insomnia: To test requests to our API.
  • MongoDB: A NoSQL database system where we'll store users (optional).

Creating the Project

First, create a new folder for your project and navigate to it from the terminal:

$ mkdir jwt-auth-api
$ cd jwt-auth-api

Next, initialize a new Node.js project by running the following command:

$ npm init -y

Add the necessary dependencies:

$ npm install express mongoose jsonwebtoken bcryptjs dotenv

Project Structure

Create the following structure within your project folder:

jwt-auth-api/
??? .env
??? app.js
??? models/
??? User.js

.env File

Create a file called .env to store sensitive variables like the secret key for signing our tokens:

JWT_SECRET=myverysecuresecret

User Model

Create the user model inside /models/User.js. This model will define the schema for our database:

const mongoose = require(mongoose);
const bcrypt = require(bcryptjs);

const UserSchema = new mongoose.Schema({
username: { type: String, required: true },
password: { type: String, required: true }
});

UserSchema.pre(save, async function(next) {
    if (!this.isModified(password)) return next();
    this.password = await bcrypt.hash(this.password, 10);
    next();
});

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

Main Code in app.js

Next, establish connections and define routes in app.js:

const express = require(express);
const mongoose = require(mongoose);
const jwt = require(jsonwebtoken);
const User = require(./models/User);
dotenv.config();

const app = express();
appp.use(express.json());
mongoose.connect(mongodb://localhost/jwt-auth, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

app.post(/register, async (req, res) => {
    const { username, password } = req.body;
bconst user = new User({ username, password });
aawait user.save();
rres.status(201).json(user);
n});
avv.post(/login, async (req, res) => {
pconst { username, password } = req.body;
tconst user = await User.findOne({ username });
sif (!user || )) {
nres.status(401).send(Invalid Credentials);
g}
dtkn = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
sres.json({ token });
n});
dapp.listen(3000, () => {
cconsole.log(Server running on port 3000);
c});
n
"> torntorln preciseonseresi ://gómico!sublime /aptodo viogato made by petor from and completeri ??????c????????? let's consider ourselves pconnectáto or by prioritizing??????????



Other articles that might interest you