How to Handle Search in Next.js: Fix and Best Practices
query parameters from useRouter() or server-side props, then filter or fetch data accordingly. Avoid directly accessing window.location to keep code universal and compatible with server rendering.Why This Happens
Developers often try to access search query parameters using window.location.search in Next.js. This causes errors because Next.js runs code on the server where window is not defined. This breaks server-side rendering and causes the app to crash or behave unexpectedly.
import { useEffect, useState } from 'react'; export default function SearchPage() { const [searchTerm, setSearchTerm] = useState(''); useEffect(() => { if (typeof window !== 'undefined') { const params = new URLSearchParams(window.location.search); setSearchTerm(params.get('q') || ''); } }, []); return <div>Search term: {searchTerm}</div>; }
The Fix
Use Next.js useRouter() hook to access query parameters safely on both server and client. This avoids direct window usage and works with server-side rendering. You can also handle search on the server with getServerSideProps for SEO benefits.
import { useRouter } from 'next/router'; export default function SearchPage() { const router = useRouter(); const { q } = router.query; return <div>Search term: {q || ''}</div>; }
Prevention
Always use Next.js routing APIs like useRouter() or server-side props to access URL data. Avoid browser-only objects like window or document in components that run on the server. Use linting tools to catch unsafe code and test your app with server-side rendering enabled.
Related Errors
Common related errors include:
- Hydration mismatch: Happens when client and server render different content due to direct
windowusage. - Undefined query parameters: Occurs if you try to read query before router is ready; check
router.isReady.
Key Takeaways
useRouter() to access search query parameters safely.window.location directly in Next.js components.getServerSideProps for SEO-friendly search.router.isReady before using query parameters to avoid undefined values.