website-logomedCode

Next.js : Search & filtering in Server side Components

Learn how to implement Next.js search in Server Components efficiently. Get step-by-step tips to enhance your app's performance and UX....
MOHAMMED DAKIR| June 5, 2024
next.js
Next.js : Search & filtering in Server side Components
Share

#Next.js #filtering #Search #Sever

Introduction

In modern web development, server components and search parameters are essential for optimizing performance and enhancing user experience. React and Next.js, two of the most popular frameworks, offer robust solutions for implementing these features efficiently. This blog post will delve into the intricacies of server components, search parameters, React server components, Next.js search in server components, and filtering in server components.

Understanding Server Components

Server components are a crucial aspect of modern web applications. They enable developers to offload rendering to the server, reducing client-side load and improving application performance. By rendering components on the server, we can take advantage of server resources and deliver fully-rendered HTML to the client, leading to faster load times and a smoother user experience.

Benefits of Server Components

  1. Improved Performance: By rendering components on the server, the initial load time is significantly reduced.
  2. SEO Optimization: Server-rendered HTML is more easily indexed by search engines, improving SEO.
  3. Reduced Client-Side Complexity: Offloading rendering to the server simplifies the client-side code.

Search Parameters in Server-Side Rendering

Search parameters are essential for dynamic content rendering based on user input. They allow the server to generate content based on query parameters, enhancing the flexibility and interactivity of web applications.

1.create nextjs app by this commande :
npx create-next-app
2.create folder inside app directory app/blogs/page.jsx
3.inside api directory create search folder and create route.js

nextjs search bar

note: articles folder is an example of rest API for get data from MongoDB

this is a route.js for search API :

import Article from "@/app/module/Article";
import connect from "@/app/utils/ConnectDB";
import { NextResponse } from "next/server";

export const GET = async (request) => {
  const url = new URL(request.url);
  const query = url.searchParams.get("query");
  console.log("search query", query);
  try {
    await connect();
    const articles = await Article.find();
    const filterArticles = articles.filter((item) => {
      return item.title.toLowerCase().includes(query.toLowerCase());
    });

    return new NextResponse(JSON.stringify(filterArticles), { status: 200 });
  } catch (error) {
    return new NextResponse("error database", { status: 500 });
  }
};
4.create component folder and inside it create a search.jsx file
"use client";
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";


const SearchBar = () => {
  const [posts, setPosts] = useState([]);
  const [query, setQuery] = useState("");
  const router = useRouter();
  
  const onChangeHandle = (query) => {
    const filteredPosts = posts.filter((post) => {
      const regex = new RegExp(`${query}`, "gi");
      return post.title.match(regex);
    });
    setQuery(query);
  };
  const handleSearch = async (e) => {
    e.preventDefault();
    const res = await fetch(`/api/articles/search?query=${query}`, {
      cache: "no-store",
    });
    if (!res.ok) {
      return alert("No results found");
    }
    const searchResult = await res.json();
    if (searchResult.length ==!) {
      const firstResultId = searchResult[0].slug;
      router.push(`/blogs/${firstResultId}`);
    }
  };
  useEffect(() => {
    const handleSearch = async () => {
      try {
        const res = await fetch(`/api/posts`, {
          cache: "no-store",
        });


        if (!res.ok) {
          throw new Error("No results found");
        }


        const fetchedPosts = await res.json();
        setPosts(fetchedPosts);
      } catch (error) {
        console.error(error);
      }
    };
    handleSearch();
  }, []);
  return (
    <>
      <form
        onSubmit={handleSearch}
        className="mt-6 px-4 py-2 rounded-full max-w-2xl bg-gray-50 border flex focus-within:border-gray-300 lg:ml-12 xs:ml-0 xs:px-2 xs:py-1 dark:bg-dark dark:border-light dark:shadow-light"
      >
        <input
          type="text"
          placeholder="Search for components & templates..."
          value={query}
          onChange={(e) => onChangeHandle(e.target.value)}
          className="bg-transparent w-full focus:outline-none font-semibold border-0 focus:ring-0 px-0 py-0"
          name="topic"
        />
        <button
          type="submit"
          name="search-button"
          title="search-button"
          aria-labelledby="search-button"
          className="flex flex-row items-center hover:bg-cyan-600 justify-center px-4 rounded-full border disabled:cursor-not-allowed disabled:opacity-50 transition ease-in-out duration-150 text-base bg-mainColor text-white font-medium tracking-wide border-transparent py-1 h-[38px]"
        >
          <svg
            className="text-gray-200 h-5 w-5 p-0 fill-current hover:text-gray-600"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
            version="1.1"
            x="0px"
            y="0px"
            viewBox="0 0 56.966 56.966"
            style={{ enableBackground: "new 0 0 56.966 56.966" }}
            xmlSpace="preserve"
          >
            <path d="M55.146,51.887L41.588,37.786c3.486-4.144,5.396-9.358,5.396-14.786c0-12.682-10.318-23-23-23s-23,10.318-23,23  s10.318,23,23,23c4.761,0,9.298-1.436,13.177-4.162l13.661,14.208c0.571,0.593,1.339,0.92,2.162,0.92  c0.779,0,1.518-0.297,2.079-0.837C56.255,54.982,56.293,53.08,55.146,51.887z M23.984,6c9.374,0,17,7.626,17,17s-7.626,17-17,17  s-17-7.626-17-17S14.61,6,23.984,6z" />
          </svg>
        </button>
      </form>
    </>
  );
};
5.wrap searchbar.jsx inside blogs folder page.jsx
import React from "react
import SearchBar from "./component/Search"
 
export default function page {
 
  return (
    <div>
      <h1>search in server component</h1>
      <SearchBar/>
    </div>
  )
}

Conclusion

Mastering server components and search parameters is crucial for modern web development. By leveraging the power of React and Next.js, developers can create highly performant and interactive applications. Whether you're implementing search functionality or filtering data on the server, understanding these concepts will enable you to build more efficient and user-friendly web applications.

This website uses cookies to enhance your browsing experience, analyze site traffic, and serve better user experiences. By continuing to use this site, you consent to our use of cookies. Learn more in our cookie policy

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policy