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
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.