Loading

Quipoin Menu

Learn • Practice • Grow

express-js / ExpressJS Serving Dynamic Content
tutorial

ExpressJS Serving Dynamic Content

Imagine a news website. Every time you visit, you see the latest articles, personalized recommendations, and maybe even ads targeted to your interests. The content changes based on who you are, what time it is, or what's happening in the world. This is dynamic content content that's generated on the fly, not served as static files.

What is Dynamic Content?

Dynamic content is content that changes based on user data, time, database queries, or other factors. It's generated by the server when a request is made, rather than being pre-written as a static HTML file.

Methods for Serving Dynamic Content

In Express, there are several ways to serve dynamic content:
  1. Using Templating Engines (EJS, Pug) Generate HTML dynamically
  2. JSON APIs Send data for client-side rendering (SPAs)
  3. Streaming Send data in chunks
  4. File downloads Generate files on the fly

1. Dynamic HTML with Templating Engines

We've seen the basics. Now let's build something more realistic a blog where posts come from a database (simulated here with an array).
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

// Mock database
const posts = [
{ id: 1, title: 'First Post', content: 'This is my first post!', author: 'John', date: '2024-01-01' },
{ id: 2, title: 'Express Tutorial', content: 'Learn Express step by step...', author: 'Jane', date: '2024-01-15' },
{ id: 3, title: 'Dynamic Content', content: 'How to serve dynamic content...', author: 'John', date: '2024-02-01' }
];

// Home page - list all posts
app.get('/', (req, res) => {
res.render('index', {
siteTitle: 'My Blog',
posts: posts,
user: req.query.user || 'Guest'
});
});

// Individual post page
app.get('/post/:id', (req, res) => {
const post = posts.find(p => p.id === parseInt(req.params.id));
if (post) {
res.render('post', { post });
} else {
res.status(404).render('404', { message: 'Post not found' });
}
});

// Author page - filter by author
app.get('/author/:name', (req, res) => {
const authorPosts = posts.filter(p =>
p.author.toLowerCase() === req.params.name.toLowerCase()
);
res.render('author', {
author: req.params.name,
posts: authorPosts
});
});

Create views/index.ejs:



<%= siteTitle %>


<%= siteTitle %>


Welcome, <%= user %>!


Recent Posts



    <% posts.forEach(post => { %>

  • <%= post.title %>
    by <%= post.author %> on <%= post.date %>

  • <% }); %>



2. JSON APIs for Dynamic Data

Modern web apps often use a separate frontend (React, Vue, Angular) that fetches data via APIs. Here's how to serve JSON dynamically:
app.use(express.json());

// Get all posts (JSON)
app.get('/api/posts', (req, res) => {
// Support query parameters for filtering
const author = req.query.author;
if (author) {
const filtered = posts.filter(p => p.author === author);
return res.json(filtered);
}
res.json(posts);
});

// Get single post (JSON)
app.get('/api/posts/:id', (req, res) => {
const post = posts.find(p => p.id === parseInt(req.params.id));
if (post) {
res.json(post);
} else {
res.status(404).json({ error: 'Post not found' });
}
});

// Create new post (JSON)
app.post('/api/posts', (req, res) => {
const newPost = {
id: posts.length + 1,
title: req.body.title,
content: req.body.content,
author: req.body.author,
date: new Date().toISOString().split('T')[0]
};
posts.push(newPost);
res.status(201).json(newPost);
});

3. Dynamic File Generation

You can generate files on the fly, like CSV reports or PDFs:
app.get('/export/posts.csv', (req, res) => {
// Create CSV content
let csv = 'ID,Title,Author,Daten';
posts.forEach(post => {
csv += `${post.id},${post.title}" ${post.author} ${post.date}n`;
});

// Set headers to force download
res.setHeader('Content-Type' 'text/csv');
res.setHeader('Content-Disposition' 'attachment; filename=posts.csv');
res.send(csv);
});

4. Dynamic Content Based on User Session

Combine with sessions to personalize content:
const session = require('express-session');
app.use(session({ secret: 'secret' resave: false saveUninitialized: true }));

app.get('/dashboard' (req res) => {
if (!req.session.user) {
return res.redirect('/login');
}

// Get personalized data
const userPosts = posts.filter(p => p.author === req.session.user.name);
const recommendedPosts = getRecommendations(req.session.user);

res.render('dashboard' {
user: req.session.user
userPosts: userPosts
recommendations: recommendedPosts
});
});

5. Combining Static and Dynamic Content

Most real apps mix static and dynamic content:
// Static files (CSS images)
app.use(express.static('public'));

// Dynamic routes
app.get('/' (req res) => {
res.render('index' { dynamicData: getData() });
});

// API endpoints
app.get('/api/data' (req res) => {
res.json({ message: 'Dynamic API response' });
});

Two Minute Drill
  • Dynamic content changes based on user time or data.
  • Use templating engines to generate dynamic HTML.
  • Use JSON APIs for single-page applications.
  • Generate files (CSV PDF) dynamically when requested.
  • Combine with sessions for personalized content.
  • Most apps mix static files with dynamic routes and APIs.
  • Always validate and sanitize user input in dynamic routes.
"

Need more clarification?

Drop us an email at career@quipoinfotech.com