Getting Started with Express and Node.js - A Developer's Guide

Author avatar

Karan Salvi / June 6, 2025

Getting Started with Express and Node.js - A Developer's Guide

Getting Started with Express and Node.js

Node.js is a runtime environment that lets you run JavaScript on the server side. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.


โš™๏ธ Why Use Node.js?

  • ๐Ÿš€ Non-blocking, event-driven architecture
  • ๐Ÿ“ฆ Rich ecosystem with npm
  • ๐Ÿ’ก Single language (JavaScript) for frontend and backend
  • ๐Ÿ”„ Real-time data handling

๐Ÿงฐ Why Use Express?

  • ๐Ÿงฑ Minimalist framework
  • ๐Ÿ”ง Middleware support
  • ๐Ÿ”„ Easy routing system
  • ๐Ÿ“š Great documentation and large community

๐Ÿ”ง Installation

Create a new Node.js project:

mkdir my-express-app
cd my-express-app
npm init -y
npm install express

๐Ÿš€ Creating Your First Express Server

// app.js
const express = require("express");
const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
  res.send("Hello World from Express!");
});

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

Run it:

node app.js

๐Ÿ› ๏ธ Handling Routes

app.get("/about", (req, res) => {
  res.send("About Page");
});

app.post("/submit", (req, res) => {
  res.send("Form submitted");
});

๐Ÿ“ฆ Using Middleware

Middleware are functions that have access to request and response objects.

app.use(express.json());

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

๐Ÿ“‚ Serving Static Files

app.use(express.static("public"));

Put files in the public/ folder to serve them directly.


๐Ÿงฉ Using Routers

// routes/userRoutes.js
const express = require("express");
const router = express.Router();

router.get("/", (req, res) => res.send("User Home"));
router.get("/:id", (req, res) => res.send(`User ID: ${req.params.id}`));

module.exports = router;

// In app.js
const userRoutes = require("./routes/userRoutes");
app.use("/users", userRoutes);

๐Ÿงช Error Handling

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});

๐Ÿ” Environment Variables

Install dotenv:

npm install dotenv

Use it:

require("dotenv").config();
const PORT = process.env.PORT || 3000;

๐ŸŒ Connecting to MongoDB (Quick Example)

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/myapp");

๐Ÿ“ Suggested Project Structure

my-express-app/
โ”œโ”€โ”€ app.js
โ”œโ”€โ”€ routes/
โ”‚   โ””โ”€โ”€ userRoutes.js
โ”œโ”€โ”€ controllers/
โ”œโ”€โ”€ models/
โ”œโ”€โ”€ middlewares/
โ”œโ”€โ”€ public/
โ””โ”€โ”€ .env