Sling Academy
Home/Next.js/Next.js 14: How to Access Search Params in Route Handlers

Next.js 14: How to Access Search Params in Route Handlers

Last updated: December 18, 2023

Next.js 13 and 14 introduced a new feature called Route Handler, which allows you to create custom request handlers for a given route using the Web Request and Response APIs.

One of the common tasks you may want to perform in a Route Handler is to extract the search params (query string), which are the key-value pairs that appear after the ? in the URL. For example, in the URL http://localhost:3000/api?name=Wolf&age=35, the search params are name=Wolf and age=35. In the step-by-step example below, I will show you how to access the search params in a Route Handler using the NextRequest and Response objects.

Step-by-step example

1. First of all, let’s create a Route Handler. To do so, you need to define a route.js or route.ts file inside the /app directory, and export a function named after the HTTP method you want to handle, such as GET, POST, PUT, etc.

// app/api/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
 /* ...*/
}

2. To access the search parameters, you need to use the NextRequest object, which is an extension of the native Request object. The NextRequest object has a nextUrl property that returns a NextURL object, which contains information about the request URL. The NextURL object has a searchParams property that returns a read-only version of the URLSearchParams interface, which provides methods for reading and manipulating the query string.

// app/api/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  // get the search params as a URLSearchParams object
  const searchParams = request.nextUrl.searchParams;

  // get the values of the name and age parameters
  const name = searchParams.get('name');
  const age = searchParams.get('age');

  // log the name and age to the console
  console.log({ name, age });
}

3. After accessing and extracting the necessary information from the search params, you are very likely to return a response. To do so, you need to use the Response or NextResponse object, which are extensions of the native Response object. The Response object has a json() method that returns a response with the given JSON object as the body.

Here’s the final code:

// app/api/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  // get the search params as a URLSearchParams object
  const searchParams = request.nextUrl.searchParams;

  // get the values of the name and age parameters
  const name = searchParams.get('name');
  const age = searchParams.get('age');

  // log the name and age to the console
  console.log({ name, age });

  // return the name and age as a JSON response
  return Response.json({ name, age });
}

4. To test the Route Handler, you can use an HTTP tool like Postman or curl to send a GET request to the /api route with some search params in the URL. For example, using curl, you can run the following command in a terminal:

curl -s -X GET 'http://localhost:3000/api?name=Wolf&age=35'

Output:

{"name":"Wolf","age":"35"}

Afterword

This article has shown you how to extract the search params (query string) in Route Handlers in Next.js 14 using the NextRequest and Response objects. I hope this helps you with your project. If you have any questions or feedback, please let me know by leaving a comment. Happy coding & have a nice day. Goodbye and see you again in other Next.js tutorials on Sling Academy!

Next Article: The Ultimate Guide to Managing Cookies in Next.js 14

Previous Article: Next.js: How to Extract Request Headers (4 Approaches)

Series: Route Handlers and API Routes in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported