Skip to content
Watch the complete Next.js 15 course on YouTube

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:

app/api/comments/route.ts
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:

app/api/comments/route.ts
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/comments returns all comments
  • /api/comments?query=first returns only comments containing “first”
  • /api/comments?query=ir returns 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 exists
const hasQuery = searchParams.has("query");
// Get all values for a parameter that appears multiple times
const tags = searchParams.getAll("tag");
// Get all parameter keys
const keys = Array.from(searchParams.keys());
// Get all parameter entries
const entries = Array.from(searchParams.entries());

Good to know

  • Query parameters are always optional
  • Use NextRequest from next/server instead of the standard Request type
  • Parameter values are always strings
  • Query parameters are case-sensitive
  • Use query parameters for features like search, filtering, sorting, and pagination