Backend Development with Node.js: Basics

Node.js is an open-source platform that allows us to run JavaScript on the server side. Using JavaScript, a language typically used for front-end development, for back-end development enables developers to work more efficiently. Node.js is popular for backend development in modern web applications due to its asynchronous nature, fast performance, and vast module ecosystem.

In this blog, we will go step by step through the basics of backend development with Node.js. We’ll cover essential concepts, explain each step with examples, and provide a detailed guide suitable for both beginners and experienced developers.


1. What is Node.js?

Node.js is a platform that uses Google's V8 JavaScript engine to run JavaScript on the server side. Node.js allows developers to build scalable network applications. It works on a single thread but can handle multiple operations concurrently thanks to its non-blocking, asynchronous nature.

Key Features of Node.js:

  • Event-driven: Node.js operates on an event-driven architecture, which ensures high performance.
  • Non-blocking: Input/output (I/O) operations are handled asynchronously, making it faster and more efficient.
  • Single-threaded: Node.js works on a single thread but supports parallel processing with its modules.
  • V8 JavaScript Engine: Node.js uses Google's V8 engine, making it fast and efficient.

2. Steps to Start Backend Development with Node.js

To start backend development with Node.js, here are the steps you'll need to follow:

2.1. Installing Necessary Tools

Before you begin, you need to have Node.js installed on your system. You can download it here.

Once installed, you can verify the installation by opening your terminal and running the following commands:

node -v
npm -v

2.2. Setting Up a New Project

To start a new Node.js project, open the terminal and create a new directory for your project:

mkdir node-backend
cd node-backend

Now, initialize your project with the following command:

npm init -y

This command will create a package.json file for your project.

2.3. Creating Your First API with Express.js

One of the most popular frameworks for building backend applications in Node.js is Express.js. Express is fast, flexible, and minimal, making it an excellent choice for building APIs.

To install Express.js in your project, run:

npm install express

Then, create an app.js file in the project’s root directory and write the following basic Express.js code:

// app.js
const express = require('express');
const app = express();

// Middleware to handle JSON data
app.use(express.json());

// Basic GET request
app.get('/', (req, res) => {
    res.send('Hello, Node.js Backend!');
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}...`);
});

In the above code, a basic GET request is created that responds with "Hello, Node.js Backend!". The server will run on port 3000.


3. RESTful APIs and CRUD Operations

When developing backend applications, you’ll frequently perform CRUD (Create, Read, Update, Delete) operations. Let’s go through how to implement these operations using Express.js.

3.1. Create (Adding Data) - POST

To add data, we use POST requests. Here’s an example of a simple user creation API:

// app.js
let users = [
    { id: 1, name: 'Ali', age: 25 },
    { id: 2, name: 'Ayşe', age: 30 }
];

// Create user API (POST)
app.post('/users', (req, res) => {
    const { name, age } = req.body;
    const newUser = { id: users.length + 1, name, age };
    users.push(newUser);
    res.status(201).json(newUser);
});

In this example, a new user is added by sending a POST request with name and age in the body of the request, and the user is pushed into the users array.

3.2. Read (Fetching Data) - GET

To fetch data, we use GET requests. Here’s how you can fetch all users:

// Get all users API (GET)
app.get('/users', (req, res) => {
    res.status(200).json(users);
});

This API will return the list of all users in JSON format.

3.3. Update (Modifying Data) - PUT

To update an existing user’s data, we use PUT requests. Here’s an example of a PUT API for updating a user:

// Update user API (PUT)
app.put('/users/:id', (req, res) => {
    const { id } = req.params;
    const { name, age } = req.body;
    const user = users.find(user => user.id == id);

    if (user) {
        user.name = name || user.name;
        user.age = age || user.age;
        res.status(200).json(user);
    } else {
        res.status(404).send('User not found');
    }
});

This API updates a user’s data based on their id with the new name and age values.

3.4. Delete (Removing Data) - DELETE

To delete data, we use DELETE requests. Here’s an example of a DELETE API that removes a user:

// Delete user API (DELETE)
app.delete('/users/:id', (req, res) => {
    const { id } = req.params;
    users = users.filter(user => user.id != id);
    res.status(204).send();
});

This API removes a user from the users array based on their id.


4. Tips for Backend Development with Node.js

  1. Asynchronous Programming: Due to Node.js’s asynchronous nature, I/O operations do not block the main thread, allowing for better performance. Use callbacks, Promises, or async/await to handle asynchronous operations cleanly.

  2. Use Middleware: Express.js allows you to use middleware for handling requests. You can use middleware for tasks like user authentication, error handling, or logging.

  3. Database Integration: For real-world applications, you’ll need to integrate a database like MongoDB, PostgreSQL, or MySQL. Express.js works seamlessly with databases and allows you to perform CRUD operations on your data.

  4. Security: When developing your backend, security is essential. Use JWT (JSON Web Token) for user authentication and authorization to ensure your API is secure.


5. Conclusion

Node.js is an excellent choice for backend development due to its fast, non-blocking, and scalable architecture. By combining Express.js with Node.js, you can quickly build RESTful APIs and handle CRUD operations efficiently. The asynchronous nature of Node.js ensures high performance, even under heavy load. As the demand for full-stack JavaScript developers grows, learning Node.js for backend development becomes increasingly important.

This guide has helped you get started with backend development using Node.js and Express.js. Now you can dive deeper into more complex projects and develop full-fledged backend applications!


Visuals

  • Node.js Architecture Flowchart: A visual representation explaining Node.js’s event-driven and non-blocking architecture.
  • CRUD Operations Diagram: A step-by-step visual guide showing CRUD operations performed through the API.