BackendBeginner

Node.js & Express Basics

Build server-side applications with Node.js and Express - routing, middleware, and REST APIs.

6 hours
10 key concepts
3 in-depth sections
Official Docs

0 of 10 concepts completed (0%)

What You'll Learn

1.Express Application Setup

javascript
const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");

const app = express();

app.use(helmet()); app.use(cors({ origin: process.env.FRONTEND_URL })); app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); app.use(express.json({ limit: "10kb" }));

if (process.env.NODE_ENV !== "production") { app.use(morgan("dev")); }

app.use("/api/v1/users", require("./routes/users")); app.use("/api/v1/orders", require("./routes/orders"));

// 404 handler app.use((req, res) => { res.status(404).json({ error: "Route not found" }); });

// Global error handler (must have 4 params!) app.use((err, req, res, next) => { console.error(err.stack); const status = err.statusCode || 500; res.status(status).json({ error: process.env.NODE_ENV === "production" ? "Internal Server Error" : err.message }); });

app.listen(process.env.PORT || 3000); ```

2.Authentication Middleware

javascript

// Auth middleware const authenticate = (req, res, next) => { const token = req.headers.authorization?.split(" ")[1]; if (!token) return res.status(401).json({ error: "No token" }); try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); } catch { res.status(401).json({ error: "Invalid token" }); } };

// Role-based authorization const authorize = (...roles) => (req, res, next) => { if (!roles.includes(req.user.role)) { return res.status(403).json({ error: "Forbidden" }); } next(); };

// Protected route app.get("/api/admin/users", authenticate, authorize("admin"), async (req, res) => { const users = await User.find(); res.json({ users }); } ); ```

3.Database Integration

javascript

const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 20, idleTimeoutMillis: 30000, });

const db = { query: (text, params) => pool.query(text, params),

async transaction(callback) { const client = await pool.connect(); try { await client.query("BEGIN"); const result = await callback(client); await client.query("COMMIT"); return result; } catch (err) { await client.query("ROLLBACK"); throw err; } finally { client.release(); } } };

// Repository pattern const UserRepo = { async findById(id) { const { rows } = await db.query( "SELECT id, name, email, role FROM users WHERE id = $1", [id] ); return rows[0] || null; },

async create({ name, email, passwordHash }) { const { rows } = await db.query( "INSERT INTO users (name, email, password_hash) VALUES ($1,$2,$3) RETURNING id,name,email", [name, email, passwordHash] ); return rows[0]; }, }; ```

Code Example

const express = require("express");
const app = express();

app.use(express.json());

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

// Routes
app.get("/api/users", (req, res) => {
  res.json({ users: [] });
});

app.post("/api/users", (req, res) => {
  const { name, email } = req.body;
  res.status(201).json({ id: 1, name, email });
});

app.listen(3000, () => console.log("Server running"));

Pro Tips

  • 1Always validate and sanitize user input before using it in database queries, file paths, or shell commands.
  • 2Use environment variables for all secrets. Never hardcode them. Use dotenv for development, platform secrets for production.
  • 3Express error-handling middleware must have exactly 4 parameters: (err, req, res, next). Missing any one makes Express skip it.
  • 4Use morgan for HTTP logging in development and pino/winston in production console.log doesn't belong in production servers.

Topics Covered

Node.jsExpressREST API

Continue Learning

Explore the official documentation and deepen your knowledge with real-world practice.

Explore the Full Portfolio

This is the complete portfolio of Sufi Khan Sulaiman, a technology leader specialising in B2B commerce and digital automation. Start from the Home page for the overview, then move through two decades of career experience across FLIR Systems, Lorex Technology, and 1c Platform, and the full catalogue of project case studies spanning headless commerce migrations, AI recommendation engines, and multi-channel fulfilment systems.

The skills and certifications page maps the technical and leadership capabilities behind the work, while the articles and the knowledge base break down the thinking into actionable frameworks. For hands-on learning, the tutorials and applications sections cover practical builds from front-end fundamentals to full-stack web apps.

For consulting engagement, the expertise page outlines service offerings, the ecommerce hub covers platform architecture and automation strategy, and the ecommerce guide (PDF) is a downloadable 55-page field manual. When you are ready to talk, the contact page is the direct line.