Build a Node.js Interactive Web-Based Simple Budget Tracker

Written by

in

Managing finances can feel overwhelming. Keeping track of income, expenses, and savings often involves spreadsheets, notebooks, and a lot of manual entry. Wouldn’t it be great to have a simple, intuitive tool that helps you visualize your financial health at a glance? This tutorial guides you through building a web-based budget tracker using Node.js, designed specifically for beginners and intermediate developers. We’ll break down the process step-by-step, explaining each concept in plain language with real-world examples, so you can create a practical application and learn essential Node.js skills.

Why Build a Budget Tracker?

Creating a budget tracker provides several benefits. Firstly, it allows you to gain control over your finances by visualizing where your money goes. Secondly, understanding your spending habits can help you identify areas where you can save. Thirdly, it is a fantastic learning experience for developers, offering practical experience with various web development concepts, including:

  • Node.js backend development
  • HTML, CSS, and JavaScript for the frontend
  • Basic database interaction (using a simple data structure)
  • Handling user input and data validation

This project is perfect for those looking to expand their knowledge of Node.js and web development while building something useful. The finished budget tracker will allow users to add income and expenses, view their spending history, and see a summary of their financial situation.

Prerequisites

Before we begin, ensure you have the following installed on your system:

  • Node.js and npm (Node Package Manager)
  • A text editor or IDE (e.g., VS Code, Sublime Text)
  • Basic knowledge of HTML, CSS, and JavaScript is helpful but not strictly required.

Setting Up the Project

Let’s start by creating our project directory and initializing our Node.js project. Open your terminal or command prompt and run the following commands:

mkdir budget-tracker
cd budget-tracker
npm init -y

This creates a new directory named “budget-tracker”, navigates into it, and initializes a new Node.js project. The npm init -y command creates a package.json file with default settings.

Installing Dependencies

We’ll need a few dependencies to build our budget tracker. We’ll use Express.js for our web server, and a simple templating engine to generate HTML dynamically. Run the following command to install these dependencies:

npm install express ejs
  • Express.js: A fast, unopinionated, minimalist web framework for Node.js.
  • EJS (Embedded JavaScript): A simple templating engine that allows you to generate HTML with JavaScript.

Creating the Server (server.js)

Now, let’s create the core of our application: the server. Create a file named server.js in your project directory and add the following code:

const express = require('express');
const app = express();
const port = 3000;

// Middleware to parse request bodies
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public')); // Serve static files

// Set the view engine to EJS
app.set('view engine', 'ejs');

// Sample data (in a real app, this would be a database)
let transactions = [];

// Routes
app.get('/', (req, res) => {
  res.render('index', { transactions: transactions });
});

app.post('/add', (req, res) => {
  const { description, amount, type } = req.body;
  const newTransaction = {
    description: description,
    amount: parseFloat(amount),
    type: type,
  };
  transactions.push(newTransaction);
  res.redirect('/');
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

Let’s break down this code:

  • Importing Modules: We import the express module to create our server and define routes.
  • Setting Up the App: We create an Express application instance (app) and define the port number (3000).
  • Middleware: We use middleware to parse incoming request bodies (express.urlencoded({ extended: true })) and to serve static files like CSS and JavaScript from a ‘public’ folder.
  • Setting the View Engine: We set the view engine to EJS with app.set('view engine', 'ejs');.
  • Data (transactions array): This is where our budget data will be stored. In a real-world application, you would replace this with a database connection.
  • Routes: We define routes to handle different requests, such as the home page (/) and adding transactions (/add).
  • GET Route (/): This route renders the index.ejs template, passing in the transactions data.
  • POST Route (/add): This route handles the form submission for adding a transaction. It extracts the data from the request body, creates a new transaction object, adds it to the transactions array, and redirects the user back to the home page.
  • Starting the Server: The app.listen(port, () => { ... }); starts the server and listens for incoming connections on the specified port.

Creating the Views (index.ejs)

Now we create the HTML structure for the budget tracker. Create a folder named views inside your project directory, and then create a file named index.ejs inside the views folder. Add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Budget Tracker</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    <h1>Budget Tracker</h1>

    <form action="/add" method="POST">
        <label for="description">Description:</label>
        <input type="text" id="description" name="description" required><br>

        <label for="amount">Amount:</label>
        <input type="number" id="amount" name="amount" step="0.01" required><br>

        <label for="type">Type:</label>
        <select id="type" name="type" required>
            <option value="income">Income</option>
            <option value="expense">Expense</option>
        </select><br>

        <button type="submit">Add Transaction</button>
    </form>

    <h2>Transactions</h2>
    <ul>
        <% transactions.forEach(transaction => { %>
            <li><%= transaction.description %> - <%= transaction.amount %> - <%= transaction.type %></li>
        <% }); %>
    </ul>

    <h2>Summary</h2>
    <p>Income: <%= transactions.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0).toFixed(2) %></p>
    <p>Expenses: <%= transactions.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0).toFixed(2) %></p>
    <p>Balance: <%= (transactions.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0) - transactions.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0)).toFixed(2) %></p>

</body>
</html>

This is the HTML structure that our server will render. Let’s break it down:

  • Basic HTML Structure: The standard HTML structure with a title and a link to a stylesheet (style.css).
  • Form for Adding Transactions: A form with input fields for description, amount, and type (income or expense). The action="/add" and method="POST" attributes specify where and how the form data will be sent.
  • Displaying Transactions: An unordered list (<ul>) to display the transactions. We use EJS to iterate over the transactions array and dynamically generate the list items (<li>).
  • Summary Section: Calculates and displays the total income, expenses, and balance using EJS to filter and sum the transaction data. toFixed(2) formats the numbers to two decimal places.

Adding Styles (style.css)

To make the budget tracker visually appealing, create a file named style.css inside a folder named public in your project directory. Add the following CSS code:

body {
    font-family: sans-serif;
    margin: 20px;
}

h1 {
    text-align: center;
}

form {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 5px;
}

input[type="text"], input[type="number"], select {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #3e8e41;
}

ul {
    list-style: none;
    padding: 0;
}

li {
    padding: 8px;
    border-bottom: 1px solid #eee;
}

This CSS provides basic styling for the form, the transaction list, and the summary section, making the application more user-friendly. You can customize this to fit your preferences.

Running the Application

Now, let’s run the application. Open your terminal, navigate to your project directory (budget-tracker), and execute the following command:

node server.js

This command starts the Node.js server. You should see a message in the console indicating that the server is running (e.g., “Server is running at http://localhost:3000”).

Open your web browser and go to http://localhost:3000. You should see the budget tracker interface. You can now enter transactions, and they will be displayed on the page. Remember, the data is stored in memory and will be lost when you restart the server. In a real-world application, you would use a database to persist the data.

Common Mistakes and How to Fix Them

Here are some common mistakes beginners make and how to avoid them:

  • Incorrect File Paths: Double-check the file paths, especially in the server.js file (e.g., when serving static files or loading templates). Ensure that the paths match the actual location of your files.
  • Missing Dependencies: If you get an error that a module cannot be found, make sure you’ve installed it using npm install <module-name>.
  • Incorrect Form Handling: Make sure your form’s method attribute is set to POST and that you’re correctly parsing the request body in your server code (using express.urlencoded({ extended: true })).
  • EJS Syntax Errors: Ensure your EJS syntax (e.g., <%= ... %>, <% ... %>) is correct in your index.ejs file.
  • Server Not Running: Always check the console for error messages. If the server isn’t running, it won’t respond to your browser requests. Make sure you’ve started the server using node server.js.

Enhancements and Next Steps

This is a basic budget tracker. Here are some ideas for enhancements:

  • Database Integration: Replace the in-memory transactions array with a database (e.g., MongoDB, PostgreSQL, or SQLite) to persist data.
  • User Authentication: Implement user accounts to allow multiple users to manage their budgets.
  • Data Validation: Add more robust data validation on the server-side to ensure the integrity of the data.
  • Reporting and Charting: Generate reports and charts to visualize spending habits.
  • Categories: Add the ability to categorize transactions (e.g., food, transportation, etc.).
  • Error Handling: Implement proper error handling to catch and handle potential issues gracefully.
  • Frontend Framework: Consider using a frontend framework like React, Vue, or Angular to build a more interactive user interface.

Summary / Key Takeaways

You’ve successfully built a simple web-based budget tracker using Node.js, Express.js, and EJS. You’ve learned how to set up a Node.js project, install dependencies, create a basic server, define routes, handle form submissions, and render dynamic HTML. This project provides a solid foundation for understanding the fundamentals of web development with Node.js. It also gives you a practical example of how to apply your knowledge to solve a real-world problem. By exploring the enhancements mentioned above, you can further develop your skills and create a more sophisticated and useful application. Remember to practice regularly, experiment with different features, and don’t be afraid to try new things. The more you code, the better you’ll become!

FAQ

Q: What is Node.js?

A: Node.js is a JavaScript runtime environment that allows you to execute JavaScript code on the server-side. It’s built on Chrome’s V8 JavaScript engine and is known for its non-blocking, event-driven architecture, making it efficient for building scalable network applications.

Q: What is npm?

A: npm (Node Package Manager) is the default package manager for Node.js. It allows you to easily install and manage dependencies (libraries and modules) for your Node.js projects.

Q: What is Express.js?

A: Express.js is a fast, unopinionated, minimalist web framework for Node.js. It provides a set of features to build web applications and APIs more easily.

Q: What is EJS?

A: EJS (Embedded JavaScript) is a simple templating engine that allows you to generate HTML with JavaScript. It lets you embed JavaScript code within your HTML templates to dynamically generate content.

Q: How do I deploy this application?

A: You can deploy this application to various platforms such as Heroku, AWS, or Google Cloud Platform. You’ll typically need to set up a deployment configuration, push your code to the platform, and the platform will handle the server setup and application deployment.

This project is an excellent starting point for anyone looking to understand web development with Node.js. By building this budget tracker, you’ve gained practical experience with essential concepts, and you are well-equipped to explore more advanced topics and build more complex applications. The journey of learning never truly ends; the excitement lies in the continuous exploration, the solving of new challenges, and the satisfaction of building something functional and useful. Keep coding, keep learning, and keep creating.