Code-Alongs - Node.js & Express

What is a Code-Along?

Code-Alongs are live experiences taught by expert instructors designed to prepare you for concepts found in the sprint challenges. These sessions are your opportunity to work on complex job-ready problems in a live and engaging environment.

Prepare For Success

The best Code-Along experiences happen when you are ready before coming to class. Your instructors create starting points and solutions for each Code-Along to ensure you have what you need to succeed.

Ideal Code-Along Preparation Checklist:

  • Review the core competencies before class
  • Watch the guided projects
  • Complete the checks for understanding
  • Finish your module projects

Available Code-Along Sessions

Code-Along 1: APIs

Learn how to build and interact with APIs using Node.js and Express.

Core Objectives

  • Understanding Express - Learn how Express simplifies building web servers compared to using Node.js alone
  • RESTful API Design - Apply REST principles to create intuitive and predictable API endpoints
  • Route Creation - Implement routes for handling various HTTP methods (GET, POST, PUT, DELETE)
  • Data Validation - Validate incoming request data before processing
  • API Testing - Use Postman or similar tools to test your API endpoints

Code Example - Basic Express API

const express = require('express');
const server = express();
server.use(express.json());

// Mock database
let users = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob', email: 'bob@example.com' }
];

// GET all users
server.get('/api/users', (req, res) => {
  res.status(200).json(users);
});

// GET user by ID
server.get('/api/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ message: 'User not found' });
  res.status(200).json(user);
});

// POST new user
server.post('/api/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

server.listen(5000, () => {
  console.log('Server running on port 5000');
});

Code-Along 2: Middleware

Explore middleware concepts and implementation in Express applications.

Core Objectives

  • Middleware Fundamentals - Understand what middleware is and its role in the request-response cycle
  • Built-in Middleware - Use Express's built-in middleware for common tasks
  • Custom Middleware - Create your own middleware functions for specific application needs
  • Error Handling - Implement middleware for consistent error handling
  • Authentication - Create middleware to validate user authentication

Code Example - Custom Middleware

const express = require('express');
const server = express();
server.use(express.json());

// Logging middleware
const logger = (req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
};

// Authentication middleware
const authenticate = (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader || authHeader !== 'Bearer valid-token') {
    return res.status(401).json({ message: 'Unauthorized' });
  }
  next();
};

// Apply logger middleware to all routes
server.use(logger);

// Public route
server.get('/api/public', (req, res) => {
  res.json({ message: 'This is public data' });
});

// Protected route with authentication middleware
server.get('/api/protected', authenticate, (req, res) => {
  res.json({ message: 'This is protected data' });
});

server.listen(5000, () => {
  console.log('Server running on port 5000');
});

Important Notes