Menu
CoddyTech

Search Page

Part of the Express Basics section of Coddy's Node.js journey. Lesson 23 of 23.

A search page is a form, and the server answers it like any other GET.

<form action="/books" method="get">
    <input name="author">
    <button>Find</button>
</form>

Submitting this form sends the browser to /books?author= followed by what was typed in the field named author. The route reads it from req.query. Writing the word back as the field's value keeps it visible after the search; it came from the visitor, so escape it.

challenge icon

Challenge

Easy

Recipe Box gets a search page. A visitor types a word, and the page lists the recipes whose title contains it.

  1. In server.js, above the 404 handler, add an async route for /search. It reads the word from req.query.q, or uses an empty string when there is none.
  2. The page always has a search form: <form action="/search" method="get"> with a text field named q and a button. Submitting it opens /search?q= followed by the word.
  3. The field shows the word that was searched: after searching curry, the field holds curry. Write the word into the field's value attribute, passed through escapeHtml, because it came from the visitor.
  4. Below the form, list a link for every recipe from loadRecipes() whose title contains the word, ignoring capitals: soup and SOUP both find Tomato Soup. Each link goes to the recipe's page and shows its escaped title, as on the home page: <a href="/recipes/1">Tomato Soup</a>.
  5. When a word was searched and no title contains it, show the text No recipes found instead of the list.

Try it: Press Run and send /search: the page shows the empty form. Type SOUP in the field and press the button. The page lists Tomato Soup, and the field still shows SOUP. Search pizza: No recipes found. Search fish: Fish & Chips, shown correctly. Then POST {"title": "Pea Soup", "tags": ["soup"]} to /api/recipes and search soup again: Pea Soup is in the list too.

Try it yourself

import { escapeHtml } from './html.js';
import { dayOfYear } from './day-of-year.js';
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
import recipesRouter, { loadRecipes } from './routes/recipes.js';
import reviewsRouter from './routes/reviews.js';

const app = express();

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

app.use((req, res, next) => {
    res.set('X-Request-Id', randomUUID());
    next();
});

app.use(express.json());

app.use(express.static('public'));

app.get('/', (req, res) => {
    const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
    res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});

// type('text') sends plain text, so each title shows on its own line.
app.get('/recipes', (req, res) => {
    const { tag } = req.query;
    const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
    res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});

app.get('/recipes/:id', (req, res) => {
    const recipe = recipes.find((r) => r.id === Number(req.params.id));
    if (!recipe) {
        res.status(404).send('No such recipe');
        return;
    }
    res.send(recipe.title);
});

app.use('/api/recipes', recipesRouter);
app.use('/api/recipes/:id/reviews', reviewsRouter);

app.get('/api/today', async (req, res) => {
    const day = dayOfYear(req.query.date);
    if (day === null) {
        res.status(400).json({ error: 'Use a date like 2026-03-01' });
        return;
    }
    const recipes = await loadRecipes();
    res.json(recipes[day % recipes.length]);
});

app.get('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

app.get('/menu', (req, res) => {
    res.redirect(301, '/recipes');
});

app.get('/menu/:id', (req, res) => {
    res.redirect(301, `/recipes/${req.params.id}`);
});

app.use((req, res) => {
    if (req.path.startsWith('/api/')) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    res.status(404).send('<h1>Page not found</h1><p><a href="/">Back to Recipe Box</a></p>');
});

app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).json({ error: 'Something went wrong' });
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

All lessons in Express Basics

Practice on your own: Express playground