Back to Blog
nodejs
express
backend
mongodb
May 10, 2025

Building a REST API with Node.js and Express

A step-by-step guide to creating a robust REST API using Node.js, Express, and MongoDB

M
Michael Chen
12 min read

Building a REST API with Node.js and Express

In today's web development landscape, REST APIs are the backbone of modern applications. This guide will walk you through creating a robust REST API using Node.js and Express, with MongoDB as the database.

Setting Up the Project

First, let's create a new project and install the necessary dependencies:

mkdir express-rest-api
cd express-rest-api
npm init -y
npm install express mongoose dotenv cors helmet
npm install --save-dev nodemon

Create a basic server structure:

// server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const helmet = require('helmet');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(helmet());
app.use(express.json());

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('MongoDB connection error:', err));

// Routes
app.use('/api/users', require('./routes/users'));
app.use('/api/posts', require('./routes/posts'));

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Server Error' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Creating Models

Let's create a simple user model:

// models/User.js
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

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

Setting Up Routes

Now, let's create some routes for our API:

// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');

// Get all users
router.get('/', async (req, res) => {
  try {
    const users = await User.find().select('-password');
    res.json(users);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Get user by ID
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id).select('-password');
    if (!user) return res.status(404).json({ message: 'User not found' });
    res.json(user);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Create user
router.post('/', async (req, res) => {
  const { name, email, password } = req.body;
  
  try {
    let user = await User.findOne({ email });
    if (user) return res.status(400).json({ message: 'User already exists' });
    
    user = new User({
      name,
      email,
      password // In a real app, you would hash this password
    });
    
    await user.save();
    res.status(201).json({ message: 'User created successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;

Adding Authentication

For a production API, you'd want to add authentication. Here's a simple implementation using JWT:

npm install jsonwebtoken bcryptjs
// middleware/auth.js
const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  // Get token from header
  const token = req.header('x-auth-token');
  
  // Check if no token
  if (!token) {
    return res.status(401).json({ message: 'No token, authorization denied' });
  }
  
  // Verify token
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ message: 'Token is not valid' });
  }
};

Conclusion

This is just the beginning of building a REST API with Node.js and Express. In a real-world application, you would also want to:

  • Implement input validation
  • Add comprehensive error handling
  • Create more robust authentication and authorization
  • Set up logging
  • Add rate limiting
  • Implement tests

By following these steps, you'll have a solid foundation for building scalable and maintainable REST APIs that can power your web and mobile applications.

In future articles, we'll cover advanced topics like API documentation, testing strategies, and deployment options.

M

About Michael Chen

Michael Chen is a passionate developer and technical writer at Noruj.com specializing in web development technologies.

Related Articles

No related articles found

Check out our other articles in the blog section
Browse All
Back to Blog

© 2025 Noruj.com. All rights reserved.

Made with
by the Noruj Team