,

Creating a Search Bar Using Next.js and Prisma, Including Search API Endpoint

Posted by






Build a Search Bar with Next.js and Prisma

Building a Search Bar with Next.js and Prisma (Search API endpoint)

Next.js and Prisma are powerful tools for building modern web applications. In this article, we will learn how to build a search bar using Next.js and Prisma, and create a search API endpoint for retrieving search results.

Setting up Next.js and Prisma

First, make sure you have Node.js and npm installed on your machine. Then, you can create a new Next.js project by running the following commands in your terminal:


npx create-next-app my-search-app
cd my-search-app

Next, install Prisma and set it up for your project by following the instructions on the Prisma documentation page.

Creating a Search Bar

Now that our project is set up, let’s create a search bar component in our Next.js application. We can do this by creating a new file called SearchBar.js in the components directory, and adding the following code:


import React, { useState } from 'react';

const SearchBar = ({ onSearch }) => {
const [searchTerm, setSearchTerm] = useState('');

const handleSearch = () => {
onSearch(searchTerm);
}

return (

setSearchTerm(e.target.value)}
/>

);
}

export default SearchBar;

This code creates a simple input field and a button that triggers the onSearch event with the current search term when clicked. We can now use this component in our application to build a search interface.

Creating a Search API Endpoint with Prisma

With our search bar in place, we can now create a search API endpoint using Prisma to fetch search results from our database. To do this, we need to define a new API route in our Next.js application and use Prisma to query the database for matching results.

First, create a new file called search.js in the api directory of your Next.js project. In this file, define a handler function that takes the search term as a query parameter and uses Prisma to fetch matching results from the database.


import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function handler(req, res) {
const { searchTerm } = req.query;

const results = await prisma.item.findMany({
where: {
name: {
contains: searchTerm,
mode: "insensitive"
}
}
});

res.status(200).json(results);
}

This code creates a new API route that fetches items from the database with a name containing the specified search term. We can now use this endpoint in our search bar component to fetch and display search results in our application.

Conclusion

With Next.js and Prisma, building a search bar and search API endpoint is straightforward and powerful. By following the steps outlined in this article, you can create a robust search interface for your web application and retrieve accurate search results from your database.


0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Askja
1 year ago

This is incredible!

Al
Al
1 year ago

clean, good tutorial, and easy to implement
deserve like + subscribe!!

Mohammad Malek
1 year ago

Thanks ❤

Svish85
1 year ago

Great video. Less great placement of your face, on top of the console 😛

Simon Edmund
1 year ago

Brother, thanks a lot!

Tomo
1 year ago

I was doing the exact same thing before watching this vid but for some reason when I change the query and re-search the page doesn't re-render like yours….
My code looks exactly like yours and I can't seem to figure out what's wrong…

Personal
1 year ago

i am trying to send fetch("/api/users/me") with access_token as header but when i console.log the logged in user is null

~~~
import { nextAuthOptions } from "@/app/api/auth/[…nextauth]/route";
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";

export async function GET(req: NextRequest) {
try {
const session = await getServerSession(nextAuthOptions);

console.log({ session: session });

return NextResponse.json(
{ status: 200, data: { user: "test" } },
{ status: 200 }
);
} catch (error: any) {
return NextResponse.json(
{ status: 500, error: error.message },
{ status: 500 }
);
}
}

~~~

MJ46
1 year ago

I just wanted to know what the endpoint might look like instead I watched a dude making a frontend tutorial, adding tons of complexity, this qualifies as a click bait, unccol

uiop uiop
1 year ago

is it compatible with next@latest ? 13.4.4 ?

salman sheriff
1 year ago

super useful

Cisco Ramon Sanchez
1 year ago

I don't like to handle myself the encoding and decoding of query from url. Instead I use the native api *URLSearchParams* . It parse, encode, decode has a toString method that convert the value on it into search params encoded.

bilegt sdf
1 year ago

thanks bro love it ❤

Harry Kara
1 year ago

Is it possible to use SQLite instead of PostgreSQL in this project?

Prashant
1 year ago

I have just completed the reddit react project on freecodecamp looking forward to learn more things from you brother
Btw thanks for providing knowledge for free.

Nirbhay
1 year ago

what's your theme name?

Mackenan D'souza
1 year ago

Hi I've been watching your reddit tutorial and have encountered an issue with the useCreation with Email and password ,i tried joining the discord but it wasn't letting me in ,could u please help me

vaquar shaikh
1 year ago

can you make an integraion video of this in graphql ?

Hassaan tahir
1 year ago

Bro can you build something (a website) on top of AI like using their API.
You can use any AI tool or you can combine multiple to build a new product.
Or can you make a video of 4-5 SaaS ideas build using Apis of multiple AI .. plzzz
Thanks in advance ✨

Hassaan tahir
1 year ago

Great video brother.. ✨

Maverick456
1 year ago

github link has been broken