Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 43 ยท Projects

Project: Server-Rendered Blog

Build a server-rendered blog: routes, HTML templates with escaping, pagination, a post form, redirect after POST and flash messages. Runnable stand-in renderer included.

Not every Express app is a JSON API. A server-rendered site builds HTML on the server and sends finished pages to the browser, which is great for search engines, fast first paint and simple code. In this project you build a small blog: a paginated list of posts, a page per post, a form to publish a new one, and a one-time "Post published" message.

Real Express would use a template engine such as EJS or Pug (Template Engines) and express-session for the flash message. Neither can be installed here, so the real code is read-only and the runnable stand-ins use plain template functions and a tiny session map on our mini framework. The ideas, escaping, pagination math and the POST-redirect-GET pattern, are identical.

Pages of the blog

GET / Paginated list of posts.
GET /posts/:slug One post, or a 404 page.
GET /new The form to write a post.
POST /posts Validate, save, redirect.
1 / 2

Templates are just functions

A template engine turns data into a string of HTML. At its core that is a function. Here is the layout and a post list written as plain JavaScript template literals:

JavaScript
const escapeHtml = (value) =>
  String(value).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);

const layout = (title, body, flash) => `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>${escapeHtml(title)}</title></head>
<body>
  <nav><a href="/">Home</a> ยท <a href="/new">Write</a></nav>
  ${flash ? `<p class="flash">${escapeHtml(flash)}</p>` : ''}
  ${body}
</body>
</html>`;

The most important function here is escapeHtml. A post title like <script>alert(1)</script> must reach the browser as text, not as code. EJS escapes with <%= value %>, Pug escapes with #{value}, and Handlebars with {{value}}; each also has a raw form (<%- %>, !{}, {{{ }}}) that you should use only for HTML you generated yourself. Forgetting to escape user content is how stored cross-site scripting happens (Security Best Practices).

Real Express version (read-only)

This is the shape of the blog in real Express 5 with EJS. The templates would live in views/.

JavaScript
import express from 'express';
import session from 'express-session';

const app = express();
app.set('view engine', 'ejs');
app.set('views', './views');

app.use(express.urlencoded({ extended: false }));
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));

app.use((req, res, next) => {
  res.locals.flash = req.session.flash;   // make it visible to every template
  delete req.session.flash;               // ...and show it only once
  next();
});

const PAGE_SIZE = 3;

app.get('/', (req, res) => {
  const page = Math.max(1, Number.parseInt(req.query.page, 10) || 1);
  const pages = Math.max(1, Math.ceil(posts.length / PAGE_SIZE));
  const items = posts.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
  res.render('index', { items, page, pages });
});

app.get('/posts/:slug', (req, res) => {
  const post = posts.find((p) => p.slug === req.params.slug);
  if (!post) return res.status(404).render('not-found');
  res.render('post', { post });
});

app.post('/posts', (req, res) => {
  const { title = '', body = '' } = req.body ?? {};
  if (!title.trim() || !body.trim()) {
    return res.status(422).render('new', { error: 'Title and text are required', values: { title, body } });
  }
  posts.unshift({ slug: slugify(title), title: title.trim(), body: body.trim() });
  req.session.flash = 'Post published';
  res.redirect(303, '/');
});

Notice the two flash lines: a message is written into the session before the redirect, and the very next request moves it onto res.locals and deletes it. res.locals is the object whose properties every template can see.

Pagination

Pagination needs three numbers: the current page, the page size, and the total page count. Always treat the ?page= value as untrusted input: it might be missing, 0, negative or abc. The code above clamps it with Math.max(1, parseInt(...) || 1). Also clamp the upper end, or ?page=999 shows an empty page; you can redirect to the last page or return a 404.

For links, render Previous and Next only when they make sense, and keep any other query parameters. For large tables, offset-based paging (slice, or SQL OFFSET) slows down on deep pages; a cursor ("posts older than this id") scales better. For a blog, offsets are fine.

The runnable stand-in: lists, pages and 404

The first example renders the list and the post pages with the template functions above, including pagination and a hostile title that gets escaped. It prints the interesting lines of each page rather than the full HTML.

Node.js Rendering, escaping and pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the third post: its title appears as &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt; &amp; friends, which the browser displays as harmless text. Out-of-range and non-numeric pages are clamped to a valid page instead of showing an empty list or crashing.

Forms, POST-redirect-GET and flash messages

When a user submits a form with POST and you answer with a page directly, pressing refresh makes the browser offer to resubmit the form, which creates duplicate posts. The fix is the POST-redirect-GET pattern: after a successful POST, respond with a redirect (303 See Other) to a normal GET page. See Forms, Redirects and Flash Messages for more.

sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: POST /posts (title, body)
  S-->>B: 303 Location: / (flash saved in session)
  B->>S: GET /
  S-->>B: 200 page with "Post published"
  B->>S: GET / (refresh)
  S-->>B: 200 page, flash is gone

The redirect turns the final page into a safe GET, and the flash message lives in the session for exactly one page view.

A flash message is stored on the server (keyed by a session cookie), read once on the next request, then deleted. Our stand-in uses a Map as the session store and sets a sid cookie by hand; real projects use express-session. When validation fails, do not redirect: re-render the form with status 422, an error message and the values the user typed, so nothing is lost.

Node.js POST, redirect, flash once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the five lines: the empty title gets a 422 form, the valid title a 303 redirect to /, the next GET / shows the flash, and a second GET / shows nothing, because the message was consumed.

What the stand-in leaves out

The session cookie here has no signature, expiry or Secure flag, and the session Map lives in one process's memory. Real express-session signs the cookie, supports stores such as Redis, and regenerates the id on login. There is also no CSRF protection: a real form that changes data needs a CSRF token or a SameSite cookie policy (Sessions and Login). Treat the stand-in as a teaching model of the flow, not as code to deploy.

Ideas to extend it

  • Add an edit form using POST /posts/:slug plus method override, or a small client-side fetch.
  • Move the templates into EJS or Handlebars files with a shared layout and partials.
  • Store posts in SQLite and paginate with LIMIT and OFFSET.
  • Render Markdown for post bodies, sanitizing the generated HTML.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why redirect with 303 after a successful POST?

    After the redirect the browser's current page is a GET, so a refresh only repeats a harmless GET.
  2. 2. A post title contains <script> tags. What protects visitors?

    Escaping turns the characters < > & and quotes into entities, so the browser shows them as text instead of running them.
  3. 3. What does a flash message do?

    Flash messages carry a notice across a redirect and are deleted as soon as they are read.
  4. 4. A visitor requests /?page=-5. What should the pagination code do?

    Query values are untrusted. Clamping to the valid range gives a sensible page and no errors.
  5. 5. When validation of a form fails, what is the usual response?

    Re-rendering keeps the user's input so they can fix the mistake instead of retyping everything.

Summary

  • A server-rendered page is a function from data to an HTML string; escape every dynamic value.
  • Clamp ?page= into a valid range and compute the page count from the total.
  • Use POST-redirect-GET (303) after successful form submissions.
  • Show validation errors by re-rendering the form with 422 and the submitted values.
  • Flash messages live in the session for one request cycle.
  • Real projects use a template engine and express-session; the stand-in only models the flow.

Next: Project: URL Shortener Service.