Skip to the main content

@trikinco/fullstack-components is no longer maintained.

Not Found Enhancer

Help visitors find what they were looking for and use the contents of your website URLs to create helpful suggestions and messages.

useNotFoundEnhancement hook

The useNotFoundEnhancement hook is used to scan your sitemap and fetch the not found enhancement data from the API route handler.

See Usage for a full example on making your own <NotFoundEnhancer> component.

Live Example

components/NotFoundEnhancer.tsx
'use client'
 
import { useNotFoundEnhancement } from '@trikinco/fullstack-components/client'
import Link from 'next/link'
 
export function NotFoundEnhancer() {
  const { data, isLoading } = useNotFoundEnhancement()
  const hasUrlSuggestions =
    data?.bestAlternateUrls && data.bestAlternateUrls.length > 0
 
  if (!data || isLoading) {
    return <p>Please wait, checking for other solutions...</p>
  }
 
  return (
    <div className="mt-6">
      {/* A helpful message derived from inspecting the `requestedUrl` and sitemap. */}
      <p>{data?.generatedContent}</p>
 
      {hasUrlSuggestions && (
        <>
          <p className="font-bold">
            Try one of these pages instead:
          </p>
          {/* A list of the most likely suitable URLs for the visitor to navigate to. */}
          {data?.bestAlternateUrls.map((url, i) => (
            <Link href={url} key={i} className="block">
              {url}
            </Link>
          ))}
        </>
      )}
 
      {!hasUrlSuggestions && (
        <p>
          Sorry we couldn't find additional pages for you to try
          this time.
        </p>
      )}
    </div>
  )
}

Setup

Add notFoundEnhancer: handleNotFoundEnhancement() to the API route handler.

Required

app/api/fsutils/[...fscomponents]/route.ts
import {
  handleFSComponents,
  handleNotFoundEnhancement,
  type FSCOptions,
} from '@trikinco/fullstack-components'
 
const fscOptions: FSCOptions = {
  notFoundEnhancer: handleNotFoundEnhancement({
    openAiApiKey: process.env.OPENAI_API_KEY || '',
    /**
     * Required.
     * Full URL of your project.
     * @example local development 'http://localhost:3000'
     * @example production 'https://example.com'
     */
    siteUrl: process.env.NEXT_PUBLIC_HOST || '',
  }),
  // Additional options and handlers...
}
 
const fscHandler = handleFSComponents(fscOptions)
 
export { fscHandler as GET, fscHandler as POST }

See more details about adding environment variables

API Reference

Types

NotFoundEnhancerOptions

Not found enhancer API route handler options.
Properties

siteUrlstring

The application site URL. Used to find the sitemap, and to construct alternate URLs.
  • example'https://example.com'

openAiApiKeystring

  • default`process.env.OPENAI_API_KEY`.

NotFoundEnhancerRequestBodyinterface

Not found enhancer request body.
Properties

requestedUrlstring

The full URL being visited.
  • example'https://example.com/this-page-does-not-exist'

NotFoundEnhancerResponseinterface

Not found enhancer response body.
Properties

generatedContentstring

A helpful message derived from inspecting the `requestedUrl` and sitemap.
  • example'This page does not exist, if you are looking for the about page, you can find it at https://example.com/about'

bestAlternateUrlsarray

A list of the most likely suitable URLs for the user to visit.
  • example`['https://example.com/about', 'https://example.com/contact']`

ChatGptCompletionResponse

The response body for `getNotFoundContentGenerator` and `getNotFoundSitemapSelector`.
Properties

responseTextstring

The response text extracted from the completion message content.

tokensUsednumber

Total number of tokens used in the request (prompt + completion).

finishReasonstring

The reason the chat stopped. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.

errorMessagestring

The error message if there was an error.

Hooks

useNotFoundEnhancementfunction

import { useNotFoundEnhancement } from '@trikinco/fullstack-components/client'
A client-side fetch handler hook that finds the closest matching page to the URL that was not found, and uses the contents of your website URLs to create a helpful message.
Parameters

bodyNotFoundEnhancerRequestBody

configUseRequestConsumerConfig<NotFoundEnhancerRequestBody>

Fetch utility hook request options without the `fetcher`. Allows for overriding the default `request` config.
Returns

isLoadingboolean

Fetch loading state. `true` if the fetch is in progress.

isErrorboolean

Fetch error state. `true` if an error occurred.

errorunknown

Fetch error object if `isError` is `true`

dataNotFoundEnhancerResponse | undefined

Fetch response data if the fetch was successful.

refetchfunction

Refetches the data.
returnsundefined

Utilities

getNotFoundContentGeneratorfunction

import { getNotFoundContentGenerator } from '@trikinco/fullstack-components'
Uses the contents of your website URLs to create a helpful message that solves the user's intent or problem. Server Action that calls the third-party API directly on the server. This avoids calling the Next.js API route handler allowing for performant Server Components.
Parameters

requestNotFoundEnhancerRequestBodyrequired

optionsNotFoundEnhancerOptionsrequired

returnsPromise<ChatGptCompletionResponse>

getNotFoundSitemapSelectorfunction

import { getNotFoundSitemapSelector } from '@trikinco/fullstack-components'
Finds the best alternative urls from the sitemap that could be what the user really wanted with their requested url. Server Action that calls the third-party API directly on the server. This avoids calling the Next.js API route handler allowing for performant Server Components.
Parameters

requestNotFoundEnhancerRequestBodyrequired

optionsNotFoundEnhancerOptionsrequired

returnsPromise<ChatGptCompletionResponse>

fetchNotFoundEnhancementfunction

import { fetchNotFoundEnhancement } from '@trikinco/fullstack-components/client'
Finds the closest matching page to the URL that was not found, and uses the contents of your website URLs to create a helpful message. Client-side fetch handler that calls the internal Next.js API route handler, then the third-party API. Best used for Client Components and functionality.
Parameters

bodyNotFoundEnhancerRequestBodyrequired

configRequestConfigOnly

Fetch utility request options without the `body`
returnsPromise<NotFoundEnhancerResponse>