#Search and filtering system
1 messages · Page 1 of 1 (latest)
Hi @thin plume. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, it's possible to have the products rendered server-side on the initial load and then change it based on the search. You can use Next.js's server rendering strategies for this. There are three subsets of server rendering: Static, Dynamic, and Streaming. For your use case, you might want to consider Dynamic Rendering.
In Dynamic Rendering, useSearchParams will be available on the server during the initial server render of the Client Component. You can use this to read/write values for query param keys. Here's an example of how you can use it:
// app/dashboard/search-bar.tsx
'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
// This will be logged on the server during the initial render
// and on the client on subsequent navigations.
console.log(search)
return <>Search: {search}</>
}
// app/dashboard/page.tsx
import SearchBar from './search-bar'
export const dynamic = 'force-dynamic'
export default function Page() {
return (
<>
<nav>
<SearchBar />
</nav>
<h1>Dashboard</h1>
</>
)
}
(Source: Next.js Documentation (https://nextjs.org/docs/app/api-reference/functions/use-search-params))
For the filtering system, you can store the filter parameters in the URL. This can be done using Next.js's Edge Middleware. Here's an example of how you can filter query parameters from the URL:
import { NextRequest, NextResponse } from 'next/server'
const allowedParams = ['allowed']
export const config = {
matcher: '/',
}
export function middleware(req: NextRequest) {
const url = req.nextUrl
let changed = false
url.searchParams.forEach((_, key) => {
if (!allowedParams.includes(key)) {
url.searchParams.delete(key)
changed = true
}
})
// Avoid infinite loop by only redirecting if the query
// params were changed
if (changed) {
return NextResponse.redirect(url)
// It's also useful to do a rewrite instead of a redirect
// return NextResponse.rewrite(url)
}
}
(Source: Vercel Templates (https://vercel.com/templates/next.js/edge-functions-filter-query-params))
You can then use these filtered parameters to fetch and display the relevant products.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@thin plume kapa.ai is still learning and improving, please let us know how it did by reacting below