December 24, 2024
O. Wolfson
With the release of Next.js 15, a major paradigm shift has emerged in the handling of URL parameters in server components. This shift simplifies URL parameter extraction while leveraging promises to handle asynchronous operations efficiently. This guide will explore how to work with URL parameters in Next.js 15 and create a minimal page component to demonstrate this in practice.
searchParams
In Next.js 15, the searchParams
object is introduced to handle query parameters asynchronously in server components. Unlike its synchronous counterpart in previous versions, searchParams
in server components returns a Promise, allowing developers to handle parameters that require asynchronous resolution seamlessly.
This approach brings several benefits:
To illustrate the power of promised-based searchParams
, let’s create a minimal blog page component that extracts generic URL parameters such as page
, limit
, and search
.
async
functions to handle searchParams
promises effectively.Here is how the implementation looks:
tsximport Link from "next/link";
// Utility function to extract the first value from a string or array
function getFirstValue(param: string | string[] | undefined): string {
return Array.isArray(param) ? param[0] : param || "";
}
const BlogPage = async ({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) => {
// Await the resolution of searchParams
const params = await searchParams;
// Extract parameters with fallback defaults
const currentPage = Number(getFirstValue(params.page)) || 1;
const postsPerPage = Number(getFirstValue(params.limit)) || 10;
const searchTerm = getFirstValue(params.search);
// Mocked data fetching logic using the extracted parameters
const posts = Array.from({ length: postsPerPage }, (_, index) => ({
id: index + 1 + (currentPage - 1) * postsPerPage,
title: ,
: ,
}));
(
);
};
;
searchParams
as a PromisesearchParams
is awaited to handle it asynchronously.params
object is resolved from the Promise
to access query parameters like page
, limit
, and search
.getFirstValue
function ensures consistent handling of query parameters whether they are passed as arrays (e.g., ?category=cat1&category=cat2
) or single strings.page
and limit
are used to dynamically create a paginated list of posts.page
parameter to navigate between paginated pages.The promised-based searchParams
API in Next.js 15 marks a significant evolution in server-side parameter handling. By making query parameters inherently asynchronous, developers can now write cleaner and more robust code for handling dynamic data. This guide has demonstrated a practical approach to using this new feature, enabling you to build flexible and scalable applications effortlessly.