Article 7

Node.js and Express.js Backend Guide

Master Node.js and Express.js for backend development with this guide on server setup, routing, middleware, and best practices for building scalable APIs.

1. Introduction to Node.js and Express.js

Node.js is a JavaScript runtime built on Chrome's V8 engine, enabling server-side JavaScript development. Express.js is a minimal and flexible Node.js framework for building web applications and APIs.

Together, Node.js and Express.js provide a powerful platform for creating scalable, performant backend systems, widely used for RESTful APIs and real-time applications.

💡 Why Use Node.js and Express.js?
  • JavaScript everywhere: Unified language for frontend and backend
  • Non-blocking I/O for high performance
  • Express.js simplifies routing and middleware
  • Rich ecosystem with npm packages
  • Ideal for microservices and APIs

1.1 Key Features

  • Node.js: Asynchronous event-driven architecture
  • Express.js: Simplified routing and middleware system
  • Scalability: Handles large numbers of concurrent connections
  • Community: Extensive libraries and tools via npm

2. Setting Up a Node.js Server

Start by setting up a basic Node.js server and installing Express.js.

2.1 Initial Setup

{ "name": "my-express-app", "version": "1.0.0", "dependencies": { "express": "^4.18.2" } }

Run npm init -y to create package.json, then install Express.js with npm install express.

2.2 Basic Server

const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello, Node.js and Express.js!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

3. Express.js Basics

Express.js simplifies Node.js server development with a robust routing and middleware system.

3.1 Application Setup

const express = require('express'); const app = express(); app.use(express.json()); // Parse JSON bodies app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies app.listen(3000, () => { console.log('Server is up on port 3000'); });
💡 Pro Tip: Use express.json() to handle JSON payloads in API requests.

4. Routing in Express.js

Express.js provides a clean way to define routes for handling HTTP requests.

4.1 Basic Routing

const express = require('express'); const app = express(); app.get('/users', (req, res) => { res.json({ users: [{ id: 1, name: 'John' }] }); }); app.post('/users', (req, res) => { const user = req.body; res.json({ message: 'User created', user }); });

4.2 Route Parameters

app.get('/users/:id', (req, res) => { const userId = req.params.id; res.json({ id: userId, name: `User ${userId}` }); });

4.3 Router Module

// routes/users.js const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.json({ users: [{ id: 1, name: 'John' }] }); }); module.exports = router; // index.js const express = require('express'); const userRoutes = require('./routes/users'); const app = express(); app.use('/users', userRoutes);

5. Middleware

Middleware functions in Express.js process requests before they reach route handlers.

5.1 Custom Middleware

const express = require('express'); const app = express(); const logger = (req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }; app.use(logger); app.get('/', (req, res) => { res.send('Hello, World!'); });

5.2 Error Handling Middleware

app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Something went wrong!' }); });
⚠️ Note: Place error-handling middleware at the end of the middleware stack.

6. Database Integration

Node.js and Express.js integrate seamlessly with databases like MongoDB for building data-driven APIs.

6.1 Using MongoDB with Mongoose

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }); const UserSchema = new mongoose.Schema({ name: String, email: String }); const User = mongoose.model('User', UserSchema); app.get('/users', async (req, res) => { const users = await User.find(); res.json(users); }); app.post('/users', async (req, res) => { const user = new User(req.body); await user.save(); res.json(user); });
💡 Mongoose Benefits: Schema-based modeling, validation, and easy querying for MongoDB.

7. Error Handling

Proper error handling ensures robust and user-friendly APIs.

7.1 Async Error Handling

const asyncHandler = fn => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; app.get('/data', asyncHandler(async (req, res) => { const data = await fetchData(); res.json(data); }));

7.2 Centralized Error Handling

app.use((err, req, res, next) => { res.status(err.status || 500).json({ error: { message: err.message, status: err.status || 500 } }); });

8. Best Practices

Follow these guidelines for scalable and maintainable Node.js and Express.js applications.

8.1 Project Structure

  • Organize code into routes, controllers, and services
  • Use environment variables for configuration
  • Implement modular routing with Express Router

8.2 Common Pitfalls

⚠️ Common Mistakes:
  • Not handling async errors properly
  • Ignoring middleware order
  • Not securing APIs (e.g., missing CORS or helmet)
  • Hardcoding sensitive data

8.3 Security Practices

const helmet = require('helmet'); const cors = require('cors'); app.use(helmet()); // Secure HTTP headers app.use(cors()); // Enable CORS app.use(express.json({ limit: '10kb' })); // Limit payload size

9. Conclusion

Node.js and Express.js provide a powerful platform for building scalable, performant backend systems. By mastering server setup, routing, middleware, and database integration, you can create robust APIs for modern web applications.

Key takeaways:

  • Node.js enables JavaScript on the server with non-blocking I/O
  • Express.js simplifies routing and middleware
  • Modular routing and middleware enhance maintainability
  • Database integration with MongoDB is seamless
  • Security and error handling are critical for production

Start building Node.js and Express.js APIs by creating small projects, integrating databases, and applying security best practices.

🎯 Next Steps:
  • Build a RESTful API with Express.js and MongoDB
  • Create a custom middleware for authentication
  • Deploy a Node.js app to a cloud platform like Heroku