Skip to the main content

@trikinco/fullstack-components is no longer maintained.

Usage

Learn the basics of working with fullstack-components.

Styling

Fullstack Components uses Tailwind as the default styling engine, but it's an optional dependency. This allows you to use whatever styling approach you prefer.

Configuring Tailwind source paths

If you're using any of the prebuilt components as-is, you need to add fullstack-components as a content source for your project, to ensure all the Tailwind class names are included.

tailwind.config.ts
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './src/**/*.{js,ts,jsx,tsx,mdx}',
    './node_modules/@trikinco/fullstack-components/src/components/**/*.{js,ts,jsx,tsx}',
  ],
  // ...
}

Customizing styles with Tailwind

When using Tailwind to customize component styles, it's recommended to use the merge utility to safely combine CSS classes without style conflicts.

import { merge } from '@trikinco/fullstack-components/utils'

merge combines tailwind-merge and clsx to allow for efficient and flexible overrides.

merge example
import { Select } from '@trikinco/fullstack-components'
import { merge } from '@trikinco/fullstack-components/utils'
 
export default async function Page() {
  return (
    <Select
      prompt="The Fellowship Of The Ring"
      context="Playable character for a LOTR game"
      className={merge(
        'bg-blue-800 dark:bg-blue-300',
        'dark:text-black border-none rounded-xl'
      )}
    />
  )
}

Quickstart

After installing, this page takes you through making a <NotFoundEnhancer> Component that uses your sitemap to find the closest matching page to the "not found" / 404 URL.

The component also uses the contents of your website URLs to create helpful messages for visitors.

Step 1: Generate a sitemap

You need a sitemap that the <NotFoundEnhancer> can scan in order to suggest alternative pages to navigate to.

Add a static sitemap.xml or generate it dynamically

In Next.js 14, you can generate a sitemap.xml in a few different ways. For this simple scenario, consider placing a static file in the app directory or using a sitemap.(js|ts) file for dynamic generation.

Alternatively, consider using the next-sitemap NPM package for easy sitemap creation.

Example output:

public/sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://localhost:3000</loc>
    <lastmod>2023-12-25T16:21:41.757Z</lastmod>
    <changefreq>monthly</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>http://localhost:3000/about-me</loc>
    <lastmod>2023-12-25T16:21:41.757Z</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.7</priority>
  </url>
</urlset>

Ensure your sitemap is accessible at /sitemap.xml in your application, and continue to the next step.

Step 2: Configure the API route handler

In the API route handler, add the following configuration to use the useNotFoundEnhancement hook shown later.

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 }

Remember to add NEXT_PUBLIC_HOST to your .env file, or inline in handleNotFoundEnhancement.

Not Found Enhancer requires configuration of the API handler route. Not all features require configuration, so read the documentation for each feature.

Step 3: Create the Client Component

The core part of the functionality is using the useNotFoundEnhancement hook to get the data you'll need.

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>
  )
}

Step 4: Create a not-found page

pages/404.tsx or app/not-found.tsx
import Link from 'next/link'
import { NotFoundEnhancer } from '@/components/NotFoundEnhancer'
 
export default function NotFoundPage() {
  return (
    <main>
      <h1>Not Found</h1>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
      <NotFoundEnhancer />
    </main>
  )
}

Now that you've created the not-found page and added the <NotFoundEnhancer>, try visiting a URL in your application that doesn't exist to see it in action.

Testing it out

For example, navigate to http://localhost:3000/about-123, or any other URL that doesn't exist in your application.

If everything works correctly you'll notice how the <NotFoundEnhancer> dynamically enhances your application's 'Not Found' page.

Keep in mind

The more pages your Next.js application has in its sitemap, the more effectively the <NotFoundEnhancer> works, providing a richer user experience.

What's next?

Congratulations on starting your journey with Fullstack Components! 🎉

You've taken the first steps towards seamlessly integrating AI capabilities into your projects. Explore the docs to discover more features that will enhance your development experience.