0
0
NextjsDebug / FixBeginner · 4 min read

How to Handle Search in Next.js: Fix and Best Practices

In Next.js, handle search by reading the 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.

javascript
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>;
}
Output
ReferenceError: window is not defined
🔧

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.

javascript
import { useRouter } from 'next/router';

export default function SearchPage() {
  const router = useRouter();
  const { q } = router.query;

  return <div>Search term: {q || ''}</div>;
}
Output
Search term: (shows the 'q' query parameter value or empty if none)
🛡️

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 window usage.
  • Undefined query parameters: Occurs if you try to read query before router is ready; check router.isReady.

Key Takeaways

Use Next.js useRouter() to access search query parameters safely.
Never use window.location directly in Next.js components.
Consider server-side data fetching with getServerSideProps for SEO-friendly search.
Check router.isReady before using query parameters to avoid undefined values.
Use linting and testing to prevent server/client code mismatches.