Hey everyone, In Part 1, we explored the fundamentals of backend development—the "brain" behind apps, including languages, frameworks, databases, servers, and APIs. We also peeked at a typical project structure. Now, it's time to get hands-on! In this Part 2, we'll build a simple Node.js and Express.js server from scratch, add some basic routes, handle environment variables for security, set up version control with Git, and even deploy it to production using a cloud platform like DigitalOcean.
By the end, you'll have a live backend app running online—demystifying that "production" fear. Let's dive in!
Prerequisites
- Node.js installed (version 18+ recommended). Download from nodejs.org.
- A code editor like VS Code.
- Basic terminal knowledge (from Part 1 or quick online refs).
- A GitHub account for version control.
- Optional: A DigitalOcean account (free trial available).
Verify Node.js and NPM:
node -v
npm -vStep 1: Setting Up Your Project
Create a new folder for your project (e.g., my-backend-app) and navigate into it:
See important terminal command guide
mkdir my-backend-app
cd my-backend-appInitialize the project with NPM (this creates package.json):
npm initEdit package.json to add a start script:
{
"name": "my-backend-app",
"version": "1.0.0",
"description": "Simple Node.js & Express backend",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Amit",
"license": "ISC"
}Install Express.js:
npm install expressStep 2: Creating Your First Express Server
Create index.js in the root folder. This is your entry point (as mentioned in Part 1's structure).
const express = require('express');
const app = express();
const port = 4000;
app.get('/', (req, res) => {
res.send('Hello from my first backend server!');
});
app.get('/twitter', (req, res) => {
res.send('<h1>Welcome to Twitter-like endpoint</h1>');
});
app.get('/login', (req, res) => {
res.send('<h1>Please login here</h1>');
});
app.get('/youtube', (req, res) => {
res.send('<h2>Chai aur Code inspired!</h2>');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});What's Happening Here?
const express = require('express');: Imports Express.const app = express();: Creates an Express app instance.app.get('/path', (req, res) => {...});: Defines GET routes.reqis the incoming request (e.g., from a browser),resis how you send back a response (text, HTML, JSON).app.listen(port, callback);: Starts the server on port 4000.
npm startVisit http://localhost:4000/ in your browser.
Try /twitter, /login, /youtube—you'll see the responses!
Pro Tip: Changes won't auto-reload. Stop the server (Ctrl+C) and restart with npm start after edits.
For development, consider tools like Nodemon (install with npm install -g nodemon, run with nodemon index.js).
Step 3: Handling JSON Responses (API Basics)
APIs often return JSON. Add this route:
app.get('/api/user', (req, res) => {
const userData = {
username: 'amitdev',
email: 'amit@example.com'
};
res.json(userData);
});Restart and visit http://localhost:4000/api/user. You'll get JSON—perfect for frontend integration!
Step 4: Securing with Environment Variables
Hardcoding secrets (like ports or DB URLs) is risky. Use .env files.
Install dotenv:
npm install dotenvCreate .env:
PORT=4000Update index.js (at the top):
require('dotenv').config();
const port = process.env.PORT || 3000; // Fallback to 3000 if not setStep 5: Version Control with Git
Initialize Git:
git initCreate .gitignore (exclude node_modules and .env):
node_modules/
.envAdd and commit:
git add .
git commit -m "Initial backend setup"Create a GitHub repo and push:
Guide: Pushing a Local Project to GitHub
1> Create a new repository on GitHub Go to GitHub and create a new repository Enter a repository name (e.g. backend_basic) Choose Public or Private Click Create repository
2> Open your terminal and navigate to your project root folder
3> git init -> To initialize the repository or It will initializes a local Git repository in your folder. git add README.md (Ignore this step as you do not want only 1 file i.e README.md to add and push on gitHub. you have to push all your files. so follow next step)
Note:-Create .gitignore before git add . (highly recommended) so you don't accidentally upload heavy or private files like node_modules or sensitive keys you have kept in .env
4> git add . -> Add all files in the current directory to staging → This stages everything (all files and folders) except items listed in .gitignore
5> git commit -m "first commit" -> Create your first commit with a descriptive message.
6> git branch -M main -> Set the branch name to main (GitHub’s default since ~2020)
7> git remote add origin https://github.com/notgetin18/backend_basic.git -> Copied from GitHub as you will get when you create a new repository. It will connect your local repository to GitHub repository you created.
8> git push -u origin main -> Push your code to GitHub for the first time. Now all your files will be uploded to github
Note:-The -u Flag: In the final step, -u stands for "upstream." You only need to use it the first time. After that, you can simply type git push to send your updates to GitHub. Note:- Checking Status: If you’re ever unsure what Git is doing, run git status. It’s the best way to see which files are staged and ready to go.
git remote add origin https://github.com/yourusername/my-backend-app.git
git branch -M main
git push -u origin mainStep 6: Deploying to Production (Using DigitalOcean)
Why deploy? To make your app accessible worldwide!
- Sign up at digitalocean.com (use referral for credits).
- Create a new "App" in the dashboard.
- Connect your GitHub repo and select the main branch.
- It auto-detects Node.js—set build command to
npm installand run command tonpm start. - Add environment variables (e.g., PORT=4000) in the app settings.
- Deploy! You'll get a URL like
your-app.ondigitalocean.app.
Test your routes on the live URL. Boom—your backend is in production!
Alternatives: Free options like Render or Vercel (for Node.js), but they may have limits. Heroku is another beginner-friendly choice.
Common Pitfalls & Best Practices
- Port Conflicts: Always use
process.env.PORTin prod. - Security: Never commit .env or secrets to Git.
- Scalability: This is basic—next parts will add middleware for auth/logging.
- Testing: Use tools like Postman to test APIs.
Wrapping Up
You've just built and deployed a real backend server! This hands-on setup ties into Part 1's concepts: Express as the framework, routes as API endpoints, and the server listening for requests. In Part 3, we'll integrate MongoDB for data storage, add CRUD operations, and handle user authentication—turning this into a full auth + CRUD API.



