πŸ““ Notes App Tutorial - Module 2

Step 2: Build the Backend API

🎯 Target Folder Structure
C:\Projects\my-notes-app\backend> tree
Folder PATH listing
Volume serial number is ABCD-1234
C:.
β”œβ”€β”€β”€node_modules
β”œβ”€β”€β”€.env
β”œβ”€β”€β”€package.json
└───server.js
πŸ–₯️ App Phase Preview
user@egotech:~/my-notes-app/backend$ npm install express mongoose dotenv cors
added 215 packages in 3s
user@egotech:~/my-notes-app/backend$ node server.js
Server is running on port 5000
MongoDB Connected!
πŸ“¦

2.1 Install Backend Packages

Ensure your terminal is inside the backend folder. We need to install our server framework (Express), database tool (Mongoose), and security/environment tools.

Terminal
cd backend
npm install express mongoose dotenv cors
βš™οΈ

2.2 Create Environment Variables

Inside the backend folder, create a new file named .env (don't forget the dot!). This stores your secret database password.

backend/.env
PORT=5000
MONGO_URI=your_mongodb_connection_string_here
πŸ–₯️

2.3 Write the Server Code

Create a new file named server.js in the backend folder. This is the main brain of our application. Paste the following code into it:

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

const app = express();

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

// Database Connection
mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log('MongoDB Connected!'))
  .catch(err => console.error(err));

// Test Route
app.get('/', (req, res) => {
  res.send('API is running...');
});

// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
πŸš€

2.4 Test the Server

Let's make sure everything works! Go back to your terminal (inside the backend folder) and run the server command.

Terminal
node server.js
Success! If you see "Server is running on port 5000", your backend foundation is completely ready.