How to Build a Compound Interest Web Application Using Next.js, Express.js, and Node.js: A Simple Guide

How to Build a Compound Interest Web Application Using Next.js, Express.js, and Node.js: A Simple Guide

To create a compound interest calculator using Next.js for the front end and Express.js for the back end, follow these steps:

Frontend (Next.js):

1. Create a new Next.js app:

npx create-next-app compound-interest-calculator-frontend
cd compound-interest-calculator-frontend

2. Create a compound interest calculator component:

Create a new file called CompoundInterestCalculator.js inside the components directory:

// components/CompoundInterestCalculator.js
import { useState } from 'react';

const CompoundInterestCalculator = () => {
  const [principal, setPrincipal] = useState('');
  const [rate, setRate] = useState('');
  const [time, setTime] = useState('');
  const [compoundFrequency, setCompoundFrequency] = useState('1');
  const [result, setResult] = useState('');

  const calculateCompoundInterest = () => {
    const p = parseFloat(principal);
    const r = parseFloat(rate) / 100;
    const t = parseFloat(time);
    const n = parseInt(compoundFrequency);

    const amount = p * Math.pow(1 + r / n, n * t);
    const interest = amount - p;
    setResult(interest.toFixed(2));
  };

  return (
    <div>
      <div>
        <label>Principal amount:</label>
        <input type="number" value={principal} onChange={(e) => setPrincipal(e.target.value)} />
      </div>
      <div>
        <label>Annual interest rate (%):</label>
        <input type="number" value={rate} onChange={(e) => setRate(e.target.value)} />
      </div>
      <div>
        <label>Time period (years):</label>
        <input type="number" value={time} onChange={(e) => setTime(e.target.value)} />
      </div>
      <div>
        <label>Compound frequency:</label>
        <select value={compoundFrequency} onChange={(e) => setCompoundFrequency(e.target.value)}>
          <option value="1">Annually</option>
          <option value="2">Semi-annually</option>
          <option value="4">Quarterly</option>
          <option value="12">Monthly</option>
        </select>
      </div>
      <button onClick={calculateCompoundInterest}>Calculate</button>
      {result && <p>Compound interest: ${result}</p>}
    </div>
  );
};

export default CompoundInterestCalculator;

3. Update the index.js page to use the CompoundInterestCalculator component:

Replace the content of pages/index.js with:

// pages/index.js
import CompoundInterestCalculator from '../components/CompoundInterestCalculator';

export default function Home() {
  return (
    <div>
      <h1>Compound Interest Calculator</h1>
      <CompoundInterestCalculator />
    </div>
  );
}

Backend (Express.js):

1. Create a new Express.js app:

Create a new directory for your backend, then navigate into it and initialize a new npm project:

mkdir compound-interest-calculator-backend
cd compound-interest-calculator-backend
npm init -y

2. Install Express.js:

npm install express

3. Create an Express server:

Create a file called server.js:

// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;

app.use(express.json());

app.post('/calculateCompoundInterest', (req, res) => {
  try {
    const { principal, rate, time, compoundFrequency } = req.body;
    const p = parseFloat(principal);
    const r = parseFloat(rate) / 100;
    const t = parseFloat(time);
    const n = parseInt(compoundFrequency);

    const amount = p * Math.pow(1 + r / n, n * t);
    const interest = amount - p;
    res.json({ interest: interest.toFixed(2) });
  } catch (error) {
    res.status(400).json({ error: 'Invalid input' });
  }
});

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

4. Run the Express server:

node server.js

Testing:

Now, start your Next.js app by running npm run dev and go to http://localhost:3000. You will see the compound interest calculator page. Type in the principal amount, yearly interest rate, and period, and choose how often it compounds. After you click the "Calculate" button, you'll see the calculated compound interest shown under the calculator.

Ensure that your Express server is running in a separate terminal window. When you click the "Calculate" button, the front end will make a POST request to the Express server to calculate the compound interest based on the provided inputs. The server will respond with the calculated compound interest, which will be displayed in the front end.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!