URL query parameters
This page explains how to work with URL query parameters in Next.js route handlers.
Understanding URL query parameters
URL query parameters allow you to pass optional data to your route handlers through the URL. They appear after a question mark (?) in the URL and are formatted as key-value pairs (e.g., ?query=value&sort=asc).
Accessing query parameters
To access query parameters in a route handler, use the NextRequest object:
import { type NextRequest } from "next/server";
export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams; const query = searchParams.get("query");
// Use the query parameter console.log(query);
return Response.json({ message: "Success" });}Filtering data with query parameters
A common use case for query parameters is filtering data:
import { type NextRequest } from "next/server";
interface Comment { id: number; text: string;}
const comments: Comment[] = [ { id: 1, text: "First comment" }, { id: 2, text: "Second comment" }, { id: 3, text: "Third comment with more text" },];
export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams; const query = searchParams.get("query");
const filteredComments = query ? comments.filter((comment) => comment.text.toLowerCase().includes(query.toLowerCase()) ) : comments;
return Response.json(filteredComments);}With this implementation:
/api/commentsreturns all comments/api/comments?query=firstreturns only comments containing “first”/api/comments?query=irreturns comments containing “ir”
Working with multiple query parameters
You can access multiple query parameters individually:
export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams;
const query = searchParams.get("query"); const sort = searchParams.get("sort"); const page = searchParams.get("page");
// Process parameters and return data // ...}Additional search parameter methods
The searchParams object provides several useful methods:
// Check if a parameter existsconst hasQuery = searchParams.has("query");
// Get all values for a parameter that appears multiple timesconst tags = searchParams.getAll("tag");
// Get all parameter keysconst keys = Array.from(searchParams.keys());
// Get all parameter entriesconst entries = Array.from(searchParams.entries());Good to know
- Query parameters are always optional
- Use
NextRequestfromnext/serverinstead of the standardRequesttype - Parameter values are always strings
- Query parameters are case-sensitive
- Use query parameters for features like search, filtering, sorting, and pagination