Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

Web Frameworks

Express.js Samples

Express.js web framework examples including Hello World, routing, middleware, and REST API

Samples

Entries inside this sample collection

CodejavascriptSimple

Express.js Hello World

Basic Express.js server setup and Hello World application

Difficulty

2/10

Estimated time

10 min

Tags

express, node.js, web server, routing

Prerequisites

Node.js basics

javascript
// Express.js Hello World Examples

// 1. Basic Hello World server
const express = require('express');
const app = express();
const port = 3000;

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

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

// 2. Hello World with different routes
app.get('/hello', (req, res) => {
    res.send('Hello, Express!');
});

app.get('/hello/:name', (req, res) => {
    res.send(`Hello, ${req.params.name}!`);
});

// 3. JSON response
app.get('/api/hello', (req, res) => {
    res.json({
        message: 'Hello, World!',
        timestamp: new Date().toISOString(),
        version: '1.0.0'
    });
});

// 4. HTML response
app.get('/html', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Hello Express</title>
        </head>
        <body>
            <h1>Hello, World!</h1>
            <p>This is an HTML response from Express.js</p>
        </body>
        </html>
    `);
});

// 5. Route parameters with validation
app.get('/users/:userId', (req, res) => {
    const userId = parseInt(req.params.userId);
    if (isNaN(userId)) {
        return res.status(400).send('Invalid user ID');
    }
    res.send(`User ID: ${userId}`);
});

// 6. Query parameters
app.get('/search', (req, res) => {
    const { q, limit = 10 } = req.query;
    const parsedLimit = Number.parseInt(String(limit), 10);
    res.json({
        query: q || 'No query provided',
        limit: Number.isNaN(parsedLimit) ? 10 : parsedLimit,
        results: [`Result for "${q}"`]
    });
});

// 7. POST request example
app.use(express.json());

app.post('/api/hello', (req, res) => {
    const { name, message } = req.body;
    res.json({
        greeting: `Hello, ${name || 'World'}!`,
        message: message || 'Welcome to Express.js',
        receivedAt: new Date().toISOString()
    });
});

// 8. Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

// 9. 404 handler
app.use((req, res) => {
    res.status(404).send('Page not found');
});
CodejavascriptIntermediate

Express Middleware Examples

Custom and built-in Express middleware for logging, authentication, and request processing

Difficulty

6/10

Estimated time

25 min

Tags

express, middleware, authentication, cors

Prerequisites

Express basics, Node.js

javascript
// Express Middleware Examples

const express = require('express');
const app = express();
const port = 3000;

// 1. Built-in middleware
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies
app.use(express.static('public')); // Serve static files

// 2. Custom logging middleware
const requestLogger = (req, res, next) => {
    const timestamp = new Date().toISOString();
    const method = req.method;
    const url = req.url;
    const ip = req.ip || req.connection.remoteAddress;

    console.log(`[${timestamp}] ${method} ${url} - IP: ${ip}`);
    next();
};

// 3. Request time middleware
const requestTime = (req, res, next) => {
    req.requestTime = new Date();
    next();
};

// 4. Authentication middleware
const authenticate = (req, res, next) => {
    const authToken = req.headers.authorization;

    if (!authToken || authToken !== 'Bearer my-secret-token') {
        return res.status(401).json({ error: 'Unauthorized' });
    }

    req.user = { id: 1, name: 'John Doe', role: 'user' };
    next();
};

// 5. Role-based access middleware
const requireRole = (role) => {
    return (req, res, next) => {
        if (!req.user || req.user.role !== role) {
            return res.status(403).json({ error: 'Forbidden - Insufficient permissions' });
        }
        next();
    };
};

// 6. Rate limiting middleware
const rateLimiter = (maxRequests = 100, windowMs = 60000) => {
    const requests = new Map();

    return (req, res, next) => {
        const ip = req.ip;
        const now = Date.now();
        const windowStart = now - windowMs;

        if (!requests.has(ip)) {
            requests.set(ip, []);
        }

        const ipRequests = requests.get(ip).filter(time => time > windowStart);

        if (ipRequests.length >= maxRequests) {
            return res.status(429).json({ error: 'Too many requests' });
        }

        ipRequests.push(now);
        requests.set(ip, ipRequests);
        next();
    };
};

// 7. CORS middleware
const cors = (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');

    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
};

// 8. Validation middleware
const validateUser = (req, res, next) => {
    const { name, email } = req.body;

    if (!name || name.length < 2) {
        return res.status(400).json({ error: 'Name must be at least 2 characters long' });
    }

    if (!email || !email.includes('@')) {
        return res.status(400).json({ error: 'Valid email is required' });
    }

    next();
};

// 9. Error handling middleware
const errorHandler = (err, req, res, next) => {
    console.error('Error:', err.stack);

    if (err.type === 'ValidationError') {
        return res.status(400).json({ error: err.message });
    }

    res.status(500).json({
        error: 'Internal server error',
        timestamp: new Date().toISOString()
    });
};

// Apply middleware globally
app.use(requestLogger);
app.use(requestTime);
app.use(cors);
app.use(rateLimiter());

// Routes with middleware
app.get('/', (req, res) => {
    res.json({
        message: 'Hello from Express!',
        requestTime: req.requestTime,
        timestamp: new Date().toISOString()
    });
});

app.get('/protected', authenticate, (req, res) => {
    res.json({
        message: 'This is a protected route',
        user: req.user
    });
});

app.get('/admin', authenticate, requireRole('admin'), (req, res) => {
    res.json({
        message: 'Admin dashboard',
        user: req.user
    });
});

app.post('/users', validateUser, (req, res) => {
    const { name, email } = req.body;
    res.status(201).json({
        message: 'User created successfully',
        user: { id: Date.now(), name, email }
    });
});

// Route that triggers an error
app.get('/error', (req, res, next) => {
    const error = new Error('Something went wrong!');
    error.type = 'CustomError';
    next(error);
});

// Apply error handling middleware
app.use(errorHandler);

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});
CodejavascriptIntermediate

Express REST API Examples

Complete REST API with CRUD operations, proper HTTP status codes, and error handling

Difficulty

7/10

Estimated time

30 min

Tags

express, rest, api, crud

Prerequisites

Express basics, HTTP methods, JSON

javascript
// Express REST API Examples

const express = require('express');
const app = express();
const port = 3000;

// Middleware
app.use(express.json());

// In-memory data store (for demonstration)
let users = [
    { id: 1, name: 'John Doe', email: 'john@example.com', age: 30 },
    { id: 2, name: 'Jane Smith', email: 'jane@example.com', age: 25 },
    { id: 3, name: 'Bob Johnson', email: 'bob@example.com', age: 35 }
];

let nextId = 4;

// Helper functions
const getUserById = (id) => users.find(user => user.id === parseInt(id));
const updateUserById = (id, updates) => {
    const index = users.findIndex(user => user.id === parseInt(id));
    if (index !== -1) {
        users[index] = { ...users[index], ...updates };
        return users[index];
    }
    return null;
};
const deleteUserById = (id) => {
    const index = users.findIndex(user => user.id === parseInt(id));
    if (index !== -1) {
        const deletedUser = users.splice(index, 1)[0];
        return deletedUser;
    }
    return null;
};

// Validation middleware
const validateUser = (req, res, next) => {
    const { name, email, age } = req.body;
    const errors = [];

    if (!name || name.trim().length < 2) {
        errors.push('Name must be at least 2 characters long');
    }

    if (!email || !email.includes('@')) {
        errors.push('Valid email is required');
    }

    if (age !== undefined && (isNaN(age) || age < 0 || age > 150)) {
        errors.push('Age must be a valid number between 0 and 150');
    }

    if (errors.length > 0) {
        return res.status(400).json({
            error: 'Validation failed',
            details: errors
        });
    }

    next();
};

// REST API Routes

// 1. GET /api/users - Get all users
app.get('/api/users', (req, res) => {
    const { page = 1, limit = 10, sort = 'id' } = req.query;
    const pageNumber = Number.parseInt(String(page), 10) || 1;
    const limitNumber = Number.parseInt(String(limit), 10) || 10;

    let filteredUsers = [...users];

    // Sorting
    filteredUsers.sort((a, b) => {
        if (a[sort] < b[sort]) return -1;
        if (a[sort] > b[sort]) return 1;
        return 0;
    });

    // Pagination
    const startIndex = (pageNumber - 1) * limitNumber;
    const endIndex = pageNumber * limitNumber;
    const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

    res.json({
        users: paginatedUsers,
        pagination: {
            page: pageNumber,
            limit: limitNumber,
            total: users.length,
            pages: Math.ceil(users.length / limitNumber)
        }
    });
});

// 2. GET /api/users/:id - Get user by ID
app.get('/api/users/:id', (req, res) => {
    const user = getUserById(req.params.id);

    if (!user) {
        return res.status(404).json({
            error: 'User not found',
            message: `User with ID ${req.params.id} does not exist`
        });
    }

    res.json(user);
});

// 3. POST /api/users - Create new user
app.post('/api/users', validateUser, (req, res) => {
    const { name, email, age } = req.body;

    // Check if email already exists
    const existingUser = users.find(user => user.email === email);
    if (existingUser) {
        return res.status(409).json({
            error: 'Email already exists',
            message: 'A user with this email already exists'
        });
    }

    const newUser = {
        id: nextId++,
        name: name.trim(),
        email: email.trim().toLowerCase(),
        age: age ? parseInt(age) : null,
        createdAt: new Date().toISOString()
    };

    users.push(newUser);

    res.status(201).json({
        message: 'User created successfully',
        user: newUser
    });
});

// 4. PUT /api/users/:id - Update user completely
app.put('/api/users/:id', validateUser, (req, res) => {
    const { name, email, age } = req.body;

    const existingUser = getUserById(req.params.id);
    if (!existingUser) {
        return res.status(404).json({
            error: 'User not found',
            message: `User with ID ${req.params.id} does not exist`
        });
    }

    // Check if email already exists for another user
    const emailUser = users.find(user => user.email === email.trim().toLowerCase() && user.id !== parseInt(req.params.id));
    if (emailUser) {
        return res.status(409).json({
            error: 'Email already exists',
            message: 'Another user with this email already exists'
        });
    }

    const updatedUser = updateUserById(req.params.id, {
        name: name.trim(),
        email: email.trim().toLowerCase(),
        age: age ? parseInt(age) : null,
        updatedAt: new Date().toISOString()
    });

    res.json({
        message: 'User updated successfully',
        user: updatedUser
    });
});

// 5. PATCH /api/users/:id - Update user partially
app.patch('/api/users/:id', (req, res) => {
    const updates = req.body;

    const existingUser = getUserById(req.params.id);
    if (!existingUser) {
        return res.status(404).json({
            error: 'User not found',
            message: `User with ID ${req.params.id} does not exist`
        });
    }

    // Validate email if provided
    if (updates.email) {
        if (!updates.email.includes('@')) {
            return res.status(400).json({
                error: 'Validation failed',
                details: ['Valid email is required']
            });
        }

        const emailUser = users.find(user => user.email === updates.email.trim().toLowerCase() && user.id !== parseInt(req.params.id));
        if (emailUser) {
            return res.status(409).json({
                error: 'Email already exists',
                message: 'Another user with this email already exists'
            });
        }
    }

    const updatedUser = updateUserById(req.params.id, {
        ...updates,
        updatedAt: new Date().toISOString()
    });

    res.json({
        message: 'User updated successfully',
        user: updatedUser
    });
});

// 6. DELETE /api/users/:id - Delete user
app.delete('/api/users/:id', (req, res) => {
    const deletedUser = deleteUserById(req.params.id);

    if (!deletedUser) {
        return res.status(404).json({
            error: 'User not found',
            message: `User with ID ${req.params.id} does not exist`
        });
    }

    res.json({
        message: 'User deleted successfully',
        user: deletedUser
    });
});

// 7. GET /api/search/users - Search users
app.get('/api/search/users', (req, res) => {
    const { q, field = 'name' } = req.query;

    if (!q) {
        return res.status(400).json({
            error: 'Query parameter is required',
            message: 'Please provide a search term using the "q" parameter'
        });
    }

    const searchResults = users.filter(user => {
        const searchField = user[field];
        return searchField && searchField.toString().toLowerCase().includes(q.toLowerCase());
    });

    res.json({
        query: q,
        field,
        results: searchResults,
        count: searchResults.length
    });
});

// 8. GET /api/stats/users - User statistics
app.get('/api/stats/users', (req, res) => {
    const totalUsers = users.length;
    const averageAge = users.reduce((sum, user) => sum + (user.age || 0), 0) / totalUsers;
    const ageGroups = {
        '18-25': users.filter(user => user.age >= 18 && user.age <= 25).length,
        '26-35': users.filter(user => user.age >= 26 && user.age <= 35).length,
        '36-45': users.filter(user => user.age >= 36 && user.age <= 45).length,
        '46+': users.filter(user => user.age >= 46).length
    };

    res.json({
        totalUsers,
        averageAge: Math.round(averageAge * 100) / 100,
        ageGroups,
        lastUpdated: new Date().toISOString()
    });
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error('Error:', err.stack);
    res.status(500).json({
        error: 'Internal server error',
        message: 'An unexpected error occurred'
    });
});

// 404 handler
app.use('*', (req, res) => {
    res.status(404).json({
        error: 'Route not found',
        message: `Route ${req.originalUrl} does not exist`
    });
});

app.listen(port, () => {
    console.log(`REST API server running at http://localhost:${port}`);
    console.log('Available endpoints:');
    console.log('  GET    /api/users');
    console.log('  GET    /api/users/:id');
    console.log('  POST   /api/users');
    console.log('  PUT    /api/users/:id');
    console.log('  PATCH  /api/users/:id');
    console.log('  DELETE /api/users/:id');
    console.log('  GET    /api/search/users');
    console.log('  GET    /api/stats/users');
});

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

Observability Debugging from Logs, Traces, Webhooks, and JSON Payloads

Parse logs, decode traces, inspect webhook/API evidence, explore JSON payloads, and extract recurring patterns before writing an incident-ready debugging note.

Hub

JSON Field Extraction, Transformation, and Provenance

Extract selected JSON fields by path, reshape the payload with JSONata, and record field-level provenance without claiming business-semantic validation.

Hub

JSON Normalization and Interchange Workflow

Turn a structured source into a checked JSON representation, then export the exact table, configuration, document, API, XML, CSON, EDN, BSON, or UBJSON form required downstream.

Home
Tools3212
Workbench
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Development

Data URI Generator

Convert files into Data URIs (Base64 or percent-encoded) for inlining images, fonts, and assets directly into HTML, CSS, or Markdown

Media

Audio Chord Progression Detector

Estimate an audio file's chord sequence locally and download CSV, JSON, SVG, and method notes in one ZIP.

Media

Audio Melody Contour Extractor

Extract a dominant melody path from audio and export MIDI, note events, a pitch contour, SVG, and JSON in one ZIP.

Media

AAC to OGG Converter

Convert AAC audio files to OGG Vorbis format with quality and channel controls

Media

Batch Audio Converter

Convert multiple audio files between different formats like MP3, WAV, FLAC, AAC, OGG, Opus with quality settings and batch processing

Media

Batch Podcast Publisher Pack

Normalize a batch of podcast episodes, apply metadata and chapters, and package validated delivery files in one ZIP.

Media

Audio Change Bitrate

Re-encode audio to a new bitrate while keeping the same format

Media

Audio Channel Resample

Change the number of channels (mono/stereo) while keeping the same format

DevOps

ELK Stack Log Analysis Samples

Comprehensive ELK Stack (Elasticsearch, Logstash, Kibana) samples for log aggregation, processing, and visualization in distributed systems

Monitoring & Observability

Datadog Monitoring Samples

Comprehensive Datadog monitoring and observability configuration examples including APM, logs, metrics, and dashboards

Error Monitoring

Sentry Error Tracking Samples

Comprehensive Sentry error tracking and performance monitoring setup with SDK integrations for various platforms

Web Frameworks

Hono Samples

Hono ultra-fast web framework examples including routing, middleware, and deployment

Kotlin

Android Web Features Kotlin Samples

Android Kotlin web-specific examples including URL routing, middleware handling, and static file serving

Objective-C

macOS Web Features Objective-C Samples

macOS Objective-C web features examples including URL routing, middleware, and static file serving