Next.js Discord

Discord Forum

How to Build a Search Form with API Integration Using Next.js 14+?

Answered
Band-tailed Pigeon posted this in #help-forum
Open in Discord
Band-tailed PigeonOP
Hi. ^_^
I'm working on a new project using Next.js 14 or above, where I need to implement a search functionality. The layout is as follows:

On the left side, I have a search form where the user enters their query and submits it.
On the right side, the content is updated and displayed based on the results returned from an API.
The key requirement is that the right side depends on the search query submitted from the left side. I was wondering if it would make sense to update the URL (e.g., include the search parameters in the query string) after the form is submitted, and then let the right side read from the URL to fetch and display the data. This way, the state can be shareable and easier to handle if the page is refreshed or shared with others.

Would this approach be better than just passing the state directly via React, or are there better practices for handling this kind of feature using the latest features of Next.js 14+ (for example, Server Actions)? Also, if you have a detailed implementation guide or suggestions on the best architecture to achieve this, I'd greatly appreciate it.
Answered by Asian black bear
You are correct, just having it in the URL makes it the most convenient. You can use next/form for a progressively enhanced form if you don't want to update in realtime while typing and for the rest just read this which covers this particular use-case: https://nextjs-faq.com/sharing-client-side-state-with-server-components
View full answer

2 Replies

Asian black bear
You are correct, just having it in the URL makes it the most convenient. You can use next/form for a progressively enhanced form if you don't want to update in realtime while typing and for the rest just read this which covers this particular use-case: https://nextjs-faq.com/sharing-client-side-state-with-server-components
Answer
Asian black bear
The example code has a lot of boilerplate to allow for changes while typing; a conventional next/form with a single input field that automatically appends as search params is in many cases just enough.