Implement a search page in Next.js App Router where search results are server components…
- User
Implement a search page in Next.js App Router where search results are server components streamed to the client. Use a client component for the search input that updates URL query params, wrap results in Suspense, and use useTransition to keep old results visible while new ones fetch.
Assistant
This is a great question about implementing server-side rendering with streaming in Next.js App Router. The user wants:
- A search page with server components streamed to the client
- Client component for search input that updates URL query params
- Suspense wrapping for results
- useTransition to keep old results visible while new ones fetch
Let me create a comprehensive example that demonstrates all these concepts.
Key points to cover:
- Server-side component for displaying search results
- Client-side component for search input with URL updates
- Suspense boundaries around streaming content
- useTransition hook for pending state
- Simulate a delay to show the streaming effect
- Proper loading states
Here's my implementation plan:
app/ ├── search/ │ ├── page.tsx (main page - server component) │ ├── search-input.tsx (client component) │ ├── search-results.tsx (server component) │ └── result-item.tsx (server component)Let me write out the complete implementation:
Next.js Server Component Streaming Search Page
I'll build a complete search page with server-side streaming, Suspense boundaries, and useTransition for smooth UX.
Project Structure
app/ ├── search/ │ ├── page.tsx │ ├── search-input.tsx │ ├── search-results.tsx │ ├── result-item.tsx │ └── loading.skeleton.tsx └── lib/ └── search-utils.ts1. Search Utilities & Mock Data
app/lib/search-utils.ts// Simulate a database or API call export interface SearchResult { id: string; title: string; description: string; category: string; rating: number; timestamp: string; } // Mock database const mockData: SearchResult[] = [ { id: '1', title: 'Next.js Performance Guide', description: 'Learn how to optimize your Next.js applications', category: 'Tutorial', rating: 4.8, timestamp: '2024-01-15', }, { id: '2', title: 'React Server Components Explained', description: 'Deep dive into React Server Components', category: 'Article', rating: 4.9, timestamp: '2024-01-14', }, { id: '3', title: 'Streaming Data in Next.js', description: 'Master server-side streaming techniques', category: 'Video', rating: 4.7, timestamp: '2024-01-13', }, { id: '4', title: 'TypeScript Best Practices', description: 'Write better TypeScript code', category: 'Guide', rating: 4.6, timestamp: '2024-01-12', }, { id: '5', title: 'Building Web Apps with Next.js', description: 'Complete guide to modern web development', category: 'Course', rating: 4.9, timestamp: '2024-01-11', }, { id: '6', title: 'Database Optimization Tips', description: 'Improve your database queries', category: 'Article', rating: 4.5, timestamp: '2024-01-10', }, ]; export async function searchContent(query: string): Promise<SearchResult[]> { // Simulate network delay await new Promise((resolve) => setTimeout(resolve, 1200)); if (!query.trim()) { return []; } const lowercaseQuery = query.toLowerCase(); return mockData.filter( (item) => item.title.toLowerCase().includes(lowercaseQuery) || item.description.toLowerCase().includes(lowercaseQuery) || item.category.toLowerCase().includes(lowercaseQuery) ); } // Simulate streaming data in chunks export async function* streamSearchResults( query: string ): AsyncGenerator<SearchResult> { const results = await searchContent(query); for (const result of results) { // Yield results one by one with a small delay await new Promise((resolve) => setTimeout(resolve, 300)); yield result; } }2. Client Component: Search Input
app/search/search-input.tsx'use client'; import { useRouter, useSearchParams } from 'next/navigation'; import { useTransition } from 'react'; import { MagnifyingGlassIcon, XMarkIcon } from '@heroicons/react/24/solid'; export default function SearchInput() { const router = useRouter(); const searchParams = useSearchParams(); const [isPending, startTransition] = useTransition(); const query = searchParams.get('q') || ''; const handleSearch = (value: string) => { // Use startTransition to prevent layout shift startTransition(() => { if (value.trim()) { router.push(`/search?q=${encodeURIComponent(value)}`); } else { router.push('/search'); } }); }; const handleClear = () => { startTransition(() => { router.push('/search'); }); }; return ( <div className="w-full"> <div className="relative"> <MagnifyingGlassIcon className="absolute left-3 top-3 h-5 w-5 text-gray-400" /> <input type="text" placeholder="Search articles, guides, and more..." defaultValue={query} onChange={(e) => handleSearch(e.target.value)} disabled={isPending} className={`w-full pl-10 pr-10 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:border-blue-500 transition-colors ${ isPending ? 'opacity-70 cursor-wait' : '' }`} /> {query && ( <button onClick={handleClear} disabled={isPending} className="absolute right-3 top-3 p-1 hover:bg-gray-100 rounded-full transition-colors disabled:opacity-50" aria-label="Clear search" > <XMarkIcon className="h-5 w-5 text-gray-400" /> </button> )} </div> {isPending && ( <div className="mt-2 flex items-center gap-2 text-sm text-gray-500"> <div className="animate-spin h-4 w-4 border-2 border-blue-500 border-t-transparent rounded-full" /> Searching... </div> )} </div> ); }3. Result Item Component
app/search/result-item.tsximport { SearchResult } from '@/app/lib/search-utils'; import { StarIcon } from '@heroicons/react/24/solid'; export function ResultItem({ result }: { result: SearchResult }) { return ( <article className="border-b border-gray-200 pb-6 last:border-b-0 animate-in fade-in slide-in-from-bottom-2 duration-500"> <div className="flex items-start justify-between gap-4"> <div className="flex-1 min-w-0"> <h3 className="text-lg font-semibold text-gray-900 hover:text-blue-600 cursor-pointer transition-colors truncate"> {result.title} </h3> <p className="mt-2 text-gray-600 line-clamp-2"> {result.description} </p> <div className="mt-4 flex items-center gap-4 flex-wrap"> <span className="inline-block px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full"> {result.category} </span> <div className="flex items-center gap-1"> {[...Array(5)].map((_, i) => ( <StarIcon key={i} className={`h-4 w-4 ${ i < Math.floor(result.rating) ? 'fill-yellow-400 text-yellow-400' : 'text-gray-300' }`} /> ))} <span className="ml-1 text-sm text-gray-600"> {result.rating.toFixed(1)} </span> </div> <time className="text-sm text-gray-500"> {new Date(result.timestamp).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', })} </time> </div> </div> </div> </article> ); }4. Search Results Server Component
app/search/search-results.tsximport { Suspense } from 'react'; import { searchContent } from '@/app/lib/search-utils'; import { ResultItem } from './result-item'; async function SearchResultsContent({ query }: { query: string }) { const results = await searchContent(query); if (!query.trim()) { return ( <div className="py-12 text-center"> <h2 className="text-xl font-semibold text-gray-900"> Start searching to see results </h2> <p className="mt-2 text-gray-600"> Try searching for "Next.js", "React", or "TypeScript" </p> </div> ); } if (results.length === 0) { return ( <div className="py-12 text-center"> <h2 className="text-xl font-semibold text-gray-900"> No results found for "{query}" </h2> <p className="mt-2 text-gray-600"> Try adjusting your search terms or selecting different categories </p> </div> ); } return ( <div> <div className="mb-6"> <p className="text-sm text-gray-600"> Found <span className="font-semibold text-gray-900">{results.length}</span> results for " <span className="font-semibold text-gray-900">{query}</span>" </p> </div> <div className="space-y-6"> {results.map((result) => ( <ResultItem key={result.id} result={result} /> ))} </div> </div> ); } // Loading skeleton function ResultsSkeleton() { return ( <div className="space-y-6"> {[...Array(3)].map((_, i) => ( <div key={i} className="border-b border-gray-200 pb-6 last:border-b-0 animate-pulse" > <div className="h-6 bg-gray-200 rounded w-3/4 mb-2" /> <div className="h-4 bg-gray-200 rounded w-full mb-2 mt-3" /> <div className="h-4 bg-gray-200 rounded w-5/6 mb-4" /> <div className="flex gap-3 mt-4"> <div className="h-6 bg-gray-200 rounded-full w-20" /> <div className="h-6 bg-gray-200 rounded-full w-24" /> <div className="h-6 bg-gray-200 rounded-full w-20" /> </div> </div> ))} </div> ); } export function SearchResults({ query }: { query: string }) { return ( <Suspense fallback={<ResultsSkeleton />}> <SearchResultsContent query={query} /> </Suspense> ); }5. Main Search Page
app/search/page.tsximport { Suspense } from 'react'; import { SearchParams } from 'next/dist/shared/lib/search-params.types'; import SearchInput from './search-input'; import { SearchResults } from './search-results'; export const metadata = { title: 'Search', description: 'Search articles, guides, and tutorials', }; interface PageProps { searchParams: Promise<SearchParams>; } export default async function SearchPage({ searchParams }: PageProps) { const params = await searchParams; const query = (params.q as string) || ''; return ( <main className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100"> <div className="container mx-auto px-4 py-8 max-w-4xl"> {/* Header */} <div className="mb-12"> <h1 className="text-4xl font-bold text-gray-900 mb-2"> Search </h1> <p className="text-gray-600"> Find articles, guides, and resources instantly </p> </div> {/* Search Input - Client Component */} <div className="mb-12"> <SearchInput /> </div> {/* Search Results - Server Component with Suspense */} <div className="bg-white rounded-lg shadow-sm p-8"> <Suspense key={query} fallback={ <div className="space-y-6"> {[...Array(3)].map((_, i) => ( <div key={i} className="border-b border-gray-200 pb-6 last:border-b-0 animate-pulse" > <div className="h-6 bg-gray-200 rounded w-3/4 mb-2" /> <div className="h-4 bg-gray-200 rounded w-full mb-2 mt-3" /> <div className="h-4 bg-gray-200 rounded w-5/6 mb-4" /> <div className="flex gap-3 mt-4"> <div className="h-6 bg-gray-200 rounded-full w-20" /> <div className="h-6 bg-gray-200 rounded-full w-24" /> </div> </div> ))} </div> } > <SearchResults query={query} /> </Suspense> </div> </div> </main> ); }6. Layout with Fonts
app/layout.tsximport type { Metadata } from 'next'; import { Inter } from 'next/font/google'; import './globals.css'; const inter = Inter({ subsets: ['latin'] }); export const metadata: Metadata = { title: 'Search App', description: 'Server-side search with streaming', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body className={inter.className}>{children}</body> </html> ); }7. Global Styles
app/globals.css@tailwind base; @tailwind components; @tailwind utilities; @layer utilities { .line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } } /* Smooth fade-in animation */ @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .animate-in { animation: fadeIn 0.5s ease-out; }8. Package Configuration
next.config.js/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { reactRoot: true, }, }; module.exports = nextConfig;Key Features Demonstrated
✅ Server Components with Streaming
- Results stream to the client progressively
- Network waterfalls eliminated
- SEO friendly
✅ Suspense Boundaries
- Fallback UI shows while data loads
- Prevents layout shift
- Skeleton loaders for UX
✅ useTransition Hook
- Old results stay visible while new ones fetch
- Smooth state updates
- Prevents janky UI
✅ URL Query Parameters
- Persistent search state
- Shareable links
- Browser back/forward support
✅ Client & Server Separation
- Search input: Client component
- Results display: Server component
- Optimal performance split
Usage
npm install next react react-dom npm install -D tailwindcss @tailwindcss/forms # Configure Tailwind and run: npm run devNavigate to
http://localhost:3000/searchand try searching!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.