Developer Guide
Make Your Next.js App Instantly Searchable
Integrate AI-powered search in your application
Adding search functionality to your Next.js application can significantly improve user experience by making your application's data easily discoverable. With Stepsailor, you can implement an AI-powered search that understands user intent and returns relevant results without complex implementation or infrastructure.
This comprehensive guide will show you how to integrate searchable resources in your Next.js application using Stepsailor SDK, allowing your users to find content, data, and features with natural language queries.
Why Add Search to Your Application
In today's data-rich applications, users often struggle to find the information they need. An effective search solution is no longer a luxury but a necessity for modern web applications. Here's why integrating search capabilities should be a priority:
-
Make Content Discoverable: Help users find relevant information quickly, reducing frustration and increasing engagement with your application's content.
-
Improved User Experience: Provide intuitive navigation through search, allowing users to bypass complex menu structures and go directly to what they need.
-
Contextual Results: Return results that match user intent rather than just keyword matching, delivering more relevant and useful search outcomes.
-
Resource Searchability: Make your application's resources - users, documents, products, or any custom data - easily searchable, improving overall data accessibility.
-
Reduce Support Burden: When users can find answers themselves through effective search, they're less likely to require assistance, reducing support tickets.
-
Enhance User Retention: Applications that make information easy to find have higher user satisfaction and retention rates, directly impacting your bottom line.
Getting Started with Stepsailor Search
Implementing search functionality in a Next.js application has traditionally required integrating with third-party search engines, setting up indexing pipelines, and managing search infrastructure. Stepsailor simplifies this process dramatically with its SDK.
1. Install the SDK
Start by installing the Stepsailor SDK in your Next.js project:
npm install @stepsailor/sdk
This single package provides everything you need to implement AI-powered search in your application without additional dependencies or complex setup.
2. Create a Basic SDK Setup
Next, create a wrapper component that initializes the Stepsailor SDK and defines your search context:
// StepsailorSdk.tsx 'use client'; import { useEffect } from 'react'; import { CommandBarApi, setupSdk } from '@stepsailor/sdk'; export default function StepsailorSdk() { useEffect(() => { setupSdk({ companyId: 'YOUR_COMPANY_ID', deployConfigId: YOUR_DEPLOY_CONFIG_ID, apiKey: 'YOUR_API_KEY', }); const cmdBar = new CommandBarApi<{}>(); cmdBar.defineContext({}); // We'll add search resources here cmdBar.activate(); }, []); return null; }
This component handles the initialization of the search functionality. The setupSdk
function configures your Stepsailor instance with your unique credentials, while the CommandBarApi
initializes the search interface. The defineContext
method allows you to provide application-specific context to enhance search relevance.
3. Add It to Your Layout
To make search available throughout your application, add the SDK component to your layout or provider wrapper:
// layout.tsx or Providers.tsx import StepsailorSdk from '@/util/StepsailorSdk'; export default function ProviderWrapper({ children }: React.PropsWithChildren) { return ( <AuthProvider> <StepsailorSdk /> {children} </AuthProvider> ); }
This ensures that your search functionality is loaded and available on all pages that use this layout. For authentication-protected applications, you can conditionally render the SDK only for authenticated users.
Making Your Resources Searchable
The true power of Stepsailor's search functionality lies in its ability to make your application's resources searchable with minimal configuration. Unlike traditional search implementations that require complex indexing and query parsing, Stepsailor's resource-based approach allows you to define what's searchable in a declarative way.
Here's how to define searchable resources in your application:
import { CommandBarApi, z } from '@stepsailor/sdk'; function defineResources(cmdBar: CommandBarApi<{}>) { // Cache configuration for all resources const baseCacheConfig = { ttl: 1000 * 60 * 5, // 5 minutes }; // Define a User resource type cmdBar.defineResource({ typeName: 'User', name: 'User', schema: z.object({ id: z.number(), name: z.string(), email: z.string(), }), searchable: { cache: baseCacheConfig, searchFunction: async (query) => { // In a real application, you would fetch this from your API const users = [ { id: 1, name: 'John Doe', email: 'john.doe@example.com' }, { id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' }, { id: 3, name: 'Alice Johnson', email: 'alice.johnson@example.com' }, // More users... ]; return users.filter((user) => user.name.toLowerCase().includes(query.toLowerCase()) ); }, visibleInCommandBarSearch: true, mapToDisplay: (resource) => ({ imageUrl: `https://picsum.photos/seed/${resource.id}/200/300`, title: resource.name, }), }, }); // Define another resource type cmdBar.defineResource({ typeName: 'KnowledgeBase', name: 'Knowledge Base', schema: z.object({ id: z.number(), name: z.string(), }), searchable: { cache: baseCacheConfig, searchFunction: async (query) => { const knowledgeBases = [ { id: 1, name: 'Product Documentation' }, { id: 2, name: 'Company Wiki' }, { id: 3, name: 'API Documentation' }, // More knowledge bases... ]; return knowledgeBases.filter((kb) => kb.name.toLowerCase().includes(query.toLowerCase()) ); }, visibleInCommandBarSearch: true, mapToDisplay: (resource) => ({ title: resource.name, onClick() { console.log('clicked', resource); // Navigate or perform actions when a search result is clicked }, }), }, }); }
Let's break down the key aspects of making resources searchable:
Resource Schemas
Stepsailor uses Zod schemas to define the structure of your resources. This approach provides type safety and validation, ensuring that your search results match the expected format. In the example above, we've defined schemas for User and KnowledgeBase resources.
Search Functions
The searchFunction
property defines how Stepsailor will search for your resources. In a production application, this function would typically call your API to retrieve matching resources based on the user's query. The search implementation is completely customizable, allowing you to integrate with any data source or search backend.
Resource Display
The mapToDisplay
function controls how your resources appear in search results. You can customize the appearance with titles, descriptions, images, and even define click behaviors for each result.
Caching Strategy
The cache
configuration allows you to optimize performance by caching search results. This reduces the number of API calls and provides faster responses to users, especially for frequently searched terms.
Using the Search in Your Application
Once you've set up Stepsailor and defined your searchable resources, using the search is straightforward for your users:
- Press
Cmd + K
(Mac) orCtrl + K
(Windows) to open the command bar - Start typing to search your resources
- Select a result to navigate or trigger associated actions
The search functionality works out of the box, intelligently matching user queries with your defined resources. The AI-powered matching goes beyond simple string matching, understanding synonyms, related terms, and even handling typos in user queries.
Search Analytics and Improvement
To continuously improve your search experience, consider monitoring how users interact with search:
cmdBar.on('search', (query, results) => { analytics.track('search_performed', { query, resultCount: results.length, hasResults: results.length > 0 }); }); cmdBar.on('resultClick', (result) => { analytics.track('search_result_clicked', { resultType: result.type, resultId: result.id }); });
This data can help you identify common search patterns, refine your search implementation, and ensure users are finding what they need.
Further Reading: Adding Actions to Your Command Bar
Beyond search, Stepsailor allows you to define actions that users can trigger from the command bar. Here's a brief example:
import { CommandBarApi, defineSchema, fillableByAI, z } from '@stepsailor/sdk'; function defineActions(cmdBar: CommandBarApi<{}>) { cmdBar.defineAction({ name: 'createFolder', description: 'Creates a new folder with the specified name', displayName: 'Create folder', inputSchema: defineSchema({ folderName: fillableByAI( z.string().describe('The name of the folder to create') ), }), handler: async ({ folderName }, { hil }) => { const { display } = hil; display.log(`Creating folder with name ${folderName}`); // Your folder creation logic here }, }); }
For more advanced action definitions and usage patterns, check out the Stepsailor documentation.
Additional Resources
Conclusion
Implementing search functionality in your Next.js application doesn't have to be complex or time-consuming. With Stepsailor's SDK, you can add powerful, AI-enhanced search to your application with minimal effort, improving user experience and making your content more accessible.
By defining searchable resources and integrating the SDK into your layout, you can provide your users with an intuitive way to find information, navigate your application, and perform actions - all from a simple search interface.
Start enhancing your application with Stepsailor search today and see how it transforms the way users interact with your content.