Implementing Search Suggestions on the 404 Page in a Hyvä Theme
AI generated
Hyvä
phtml
Hyvä Theme
Search Suggestions on the 404 Page
implemented in a Hyvä theme

A broken link does not have to be a dead end. With GraphQL-based search suggestions, the 404 page in a Hyvä theme turns from a plain error message into an active rescue point for visitors who would otherwise bounce without a word.

12 min read 404 Page Search Suggestions

1. Why a 404 page does not have to end the customer journey

Broken links happen constantly: old backlinks from partner sites, URLs that moved after a category restructuring, discontinued products, or simply typos in a manually entered address. A 404 page that only shows an error message ends that visitor's session right at the moment they still carried purchase intent, especially when the link came from an external, well-indexed domain.

This article deliberately does not cover the visual design of an error page, but the functional intelligence behind it: instead of politely informing visitors about the error, the page analyzes the requested path and actively suggests matching products or search terms, so a lost session can, in the best case, still turn into a conversion.

2. Where the requested path comes from and how it feeds suggestions

The most valuable signal available on a 404 page is the requested path itself: a URL like /womens-running-shoes-size-9 still carries valuable, searchable terms even after the originally referenced product no longer exists. These terms can be extracted by simply splitting the path on hyphens and removing generic filler tokens such as a category ID, and used as the starting point for a search.

Other potential signal sources, such as internal search history or the referrer header, are usually either unavailable or too unreliable on a 404 page to depend on. The requested path therefore remains, in practice, the most robust and most easily accessible basis for automatically generated search suggestions.


<?php
declare(strict_types=1);

namespace Mironsoft\NotFoundSuggest\ViewModel;

use Magento\Framework\App\Request\Http;
use Magento\Framework\View\Element\Block\ArgumentInterface;

/**
 * Extracts searchable terms from the requested, not-found URL path
 * for the 404 search suggestions.
 */
class PathTokenExtractor implements ArgumentInterface
{
    /** @var string[] */
    private const IGNORE_TOKENS = ['html', 'index', 'php', 'id'];

    /**
     * @param Http $request
     */
    public function __construct(private readonly Http $request)
    {
    }

    /**
     * Returns the search terms extracted from the path.
     *
     * @return string[]
     */
    public function getSearchTokens(): array
    {
        $path = trim((string) $this->request->getPathInfo(), '/');
        $tokens = preg_split('/[-_\/]+/', $path) ?: [];
        $tokens = array_filter($tokens, static fn (string $t) => !is_numeric($t) && !in_array($t, self::IGNORE_TOKENS, true));
        return array_slice(array_values($tokens), 0, 6);
    }
}

3. GraphQL-based 'did you mean' logic: fuzzy search against the catalog

The terms extracted from the path can be queried directly against Elasticsearch or OpenSearch through the standard products query with the search argument, since the fuzzy matching logic of full-text search already lives inside the search cluster and does not need to be rebuilt separately. A typo like runing shoes instead of running shoes reliably finds the same hits through this mechanism as a correctly spelled search query would.

For display purposes, it is usually enough to cap the result list at four to six products so the page does not get overloaded. If the search returns no hits at all for a heavily mangled path, the component should not simply stay empty, it should fall back to a broader level, such as the shop's most-visited categories, so the visitor is always offered a meaningful next step.


query NotFoundSuggestions($searchTerm: String!, $pageSize: Int!) {
  products(search: $searchTerm, pageSize: $pageSize) {
    total_count
    items {
      sku
      name
      url_key
      small_image { url label }
      price_range {
        minimum_price {
          final_price { value currency }
        }
      }
    }
  }
}

4. Suggesting related search terms, not just products

Beyond concrete product suggestions, showing related search terms pays off too, similar to the 'did you mean' feature on the regular search results page. The infrastructure already in place for that, such as popular saved queries from catalogsearch_query, can be reused unchanged for the 404 context by matching the extracted path tokens against that list instead of against the product catalog itself.

Combining concrete product cards with clickable search term suggestions gives visitors two different ways out of the dead end: a direct click onto a matching product for the impatient visitor, or refining their own search through a suggested term for a visitor who does not yet know exactly what they are looking for.

5. Integrating the search suggestions as an Alpine component in the 404 template

In the Hyvä 404 template, the suggestion logic can be encapsulated as a self-contained Alpine component that automatically triggers the GraphQL request with the server-extracted tokens when the page loads, managing loading state and result independently from the rest of the page content. That separation ensures a bug in the suggestion logic can never affect the rest of the 404 page and its actual error message.

As with any Hyvä component carrying its own inline script, $hyvaCsp->registerInlineScript() has to be called after the script block, so the Content Security Policy correctly assigns the generated nonce and the component does not get silently blocked in live operation.


<div x-data="notFoundSuggestions(<?= $escaper->escapeJs(implode(',', $tokens)) ?>)" x-init="load()">
  <p x-show="isLoading" class="text-sm text-slate-500">Looking for matching alternatives ...</p>
  <div x-show="!isLoading && products.length" class="grid grid-cols-2 sm:grid-cols-4 gap-4">
    <template x-for="product in products" :key="product.sku">
      <a :href="`/${product.url_key}.html`" class="border border-slate-200 rounded-lg p-3 hover:shadow-md transition">
        <img :src="product.small_image.url" :alt="product.small_image.label" class="w-full h-auto mb-2">
        <p class="text-sm font-medium" x-text="product.name"></p>
      </a>
    </template>
  </div>
  <p x-show="!isLoading && !products.length" class="text-sm text-slate-500">
    Take a look at our most popular categories instead.
  </p>
</div>

<script>
function notFoundSuggestions(tokenCsv) {
  return {
    isLoading: true,
    products: [],
    load() {
      const searchTerm = tokenCsv.split(',').join(' ');
      fetch('/graphql', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: '{ /* NotFoundSuggestions query */ }', variables: { searchTerm, pageSize: 6 } }),
      })
        .then((response) => response.json())
        .then((data) => { this.products = data.data.products.items; })
        .finally(() => { this.isLoading = false; });
    },
  };
}
</script>

6. Performance and caching for a 404 page with dynamic suggestions

The 404 page itself is usually not meaningfully cached by the Full Page Cache, since every broken URL represents its own, individual page view. That means every single broken link triggers a live fuzzy search against the search cluster, which can add noticeable, unnecessary load for old legacy URLs that crawlers keep requesting repeatedly.

A short-lived cache of the suggestion results, keyed by the normalized path tokens, significantly reduces that load, since recurring bot requests for the same stale sitemap entry no longer trigger a fresh search every time. On top of that, a simple filter that excludes known crawler user agents from suggestion generation pays off, since bots gain nothing from personalized product suggestions anyway.

7. Tracking: making conversion rescue through search suggestions measurable

Without dedicated tracking, the success of search suggestions on the 404 page stays pure guesswork. A dedicated event fired on every click of a suggested product card or a suggested search term makes it measurable how many visitors are actually pulled back from a potential dead end, instead of only looking at the generic pageview statistics of the 404 page.

The most meaningful comparison metric is the 404 page's bounce rate before and after introducing the suggestions, since it directly shows whether the investment in the extra logic actually keeps visitors inside the shop. If the bounce rate stays stubbornly high despite the suggestions, it is worth checking whether the extracted search terms lead to relevant hits at all.

A trade publication has linked for years to a running shoe model that has since been discontinued, and the URL now leads nowhere after the last catalog cleanup. The 404 page extracts the terms running shoe and the former model name from the path, uses them to find three currently available, thematically matching successor models from the same category, and adds a link to the parent category page, so the visitor arriving through the outdated external backlink still finds a meaningful destination.

Search suggestions do not replace systematic redirect maintenance: a regular look at the 404 log reveals recurring patterns, such as an entire renamed category with dozens of affected URLs, that deserve a proper redirect rather than permanently relying on automatically generated suggestions.

9. Checklist for search suggestions on the 404 page

Search suggestions on the 404 page pay off most when path extraction, fuzzy search, performance protection, and success measurement are treated as one connected system, rather than just bolting on a few product cards. A suggestion list nobody measures stays a guess about how much value it actually creates.

The overview below summarizes the key building blocks for a solid implementation, ranked by their importance for actual conversion rescue.

Building Block Purpose Implementation Effort Impact on Conversion Rescue
Path token extraction Derive searchable terms from the broken URL Low Foundation for every further suggestion
GraphQL fuzzy search against the catalog Find matching products despite typos Medium Very high
Fallback to popular categories Avoid empty suggestion areas when there are no hits Low Medium
Additionally show related search terms Offer a second way out of the dead end Medium Medium to high
Short-lived cache for suggestion results Protect the search cluster from repeated bot requests Medium No direct conversion effect, but stability
Click tracking on suggestion elements Make the measure's success measurable Low Prerequisite for solid optimization

Mironsoft

Hyvä theme development and Luma migration

Still running Luma, or a Hyvä theme that just doesn't feel right?

We build Hyvä themes for Magento from scratch or migrate existing Luma shops cleanly, with Tailwind CSS, Alpine.js, and none of the unnecessary JavaScript baggage.

Luma-to-Hyvä Migration

Move an existing shop to Hyvä in a structured way, without losing functionality.

Custom Theme Development

Build a custom Hyvä theme from scratch based on your design.

Performance Optimization

Improve Core Web Vitals and load times in the Hyvä frontend with purpose.

10. Summary

Search Suggestions on 404 Pages

Core idea

The 404 page actively analyzes the broken path and suggests matching products instead of a plain error message.

Technical basis

Extracted path tokens run through the search cluster's existing fuzzy search, no new search logic needed.

Performance

A short-lived cache protects the search cluster from repeated bot requests against stale legacy URLs.

Success measurement

Click tracking on suggestion elements makes actual conversion rescue visible instead of a guess.

11. FAQ: Search Suggestions on 404 Pages

1Why are search suggestions on the 404 page more valuable than pure error page design?
An attractive error design only politely informs the visitor about the error, while search suggestions actively offer a way back to relevant content. Visitors arriving through an external, well-indexed backlink in particular are often still kept inside the shop this way.
2Where do the terms for the search suggestions come from?
The most important source is the requested, not-found URL path itself, which yields searchable terms by splitting it on hyphens and removing generic filler tokens. Other signals like the referrer or search history are usually not reliably available on a 404 page.
3Does the fuzzy search require building custom search logic?
No, the standard GraphQL products query with the search argument already uses the existing fuzzy matching logic of Elasticsearch or OpenSearch. Typos in the extracted terms still find matching hits without needing an additional search implementation.
4What happens when the search finds no hits for a heavily mangled path?
In that case the component should not stay empty, it should fall back to a broader level, such as the shop's most-visited categories. That way the visitor is always offered a meaningful next action.
5Why is it worth showing related search terms alongside product suggestions?
Product suggestions help the visitor who knows exactly what they are looking for, while search term suggestions help the visitor who still needs to refine their own search. Both paths together cover a broader range of visitor intent.
6Why should the suggestion logic be encapsulated as its own Alpine component?
A separate component ensures a bug in the suggestion logic can never affect the rest of the 404 page and its actual error message. It also lets the component be tested independently and adjusted in a targeted way when needed.
7Why isn't a 404 page with dynamic suggestions simply covered by the Full Page Cache?
Every broken URL represents its own individual page view, so classic full-page caching has little effect. A targeted, short-lived cache of the suggestion results themselves absorbs the resulting extra load on the search cluster instead.
8How do you prevent crawlers from overloading the search cluster with 404 requests?
A simple filter that excludes known crawler user agents from suggestion generation prevents unnecessary search queries, since bots gain nothing from personalized product suggestions anyway. Combined with a short-lived result cache, the extra load stays at a non-critical level.
9How do you measure whether search suggestions on the 404 page actually rescue conversions?
A dedicated click event on every suggested product card and every suggested search term makes it visible how many visitors actually use the suggestions. Comparing the 404 page's bounce rate before and after introducing the feature gives the most meaningful overall figure.
10Do search suggestions replace maintaining redirects for known broken URLs?
No, search suggestions complement the unpredictable remainder of broken links, but they do not replace systematic redirect maintenance for known, recurring patterns. A regular look at the 404 log reveals which cases deserve a proper redirect.