Next.jsRestAPI
Last updated at 2023-10-29

NextRequest Get Query Params in Next.js Typescript

ClickUp
Note
AI Status
50%
Last Edit By
Last edited time
Oct 29, 2023 04:48 AM
Metatag
Slug
nextjs-get-query-params
Writer
Published
Published
Date
Aug 30, 2023
Category
Next.js
RestAPI
As your REST API evolves, it may be necessary to implement a GET endpoint that can specify request parameters to add more information on how to return a response to the client.
In this article, you will learn how to parse the request parameter to enable the client to provide additional information that the server can use to respond.
πŸ’‘
You can jump to the How to Parse the NextRequest GET Query Parameter. below.

Rest API GET Endpoint in Next.js

In the REST API, the GET endpoint serves as a resource that can be used to fetch data from the server.
This endpoint is meant to be safe in the sense that it will not create a side effect on the server or data.
Besides being safe, the GET endpoint is idempotent, which means multiple requests with the same parameter will result in the same response.

How to Create a Next.js GET Endpoint in Typescript?

In Next.js 13, you can create a GET endpoint this way.
Suppose you need to create api/helloworld endpoint. There are two ways to create the endpoint based on your routing choice.

Specify GET Endpoint Using Next.js App Router

Create a directory in this path src/app/api/helloworld and then create route.ts inside that directory.
This directory path will determine your API path.
import { NextRequest, NextResponse } from 'next/server'; export async function GET(req: NextRequest) { try { return NextResponse.json({ message: "Hello World" }); } catch (e) { return NextResponse.json({ error: getErrorMessage(e) }, { status: 500 }); } }

Using handler Function Using Next.js Page Router

Create a file in this path src/pages/api/helloworld.ts. The path will also determine the api path.
Write this code in helloworld.ts.
import { NextApiRequest, NextApiResponse } from 'next'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method !== 'GET') { return res.status(404); } return res.status(200).json({ message: "Hello World" }); }

What is the difference?

If you choose to use the handler function, you need to mark the function with export default. While if you use GET as a function name, you should not use the default keyword.
When you violate this, Next.js will give you an error based on your wrong implementation.
When you export the handler without using the default keyword.
It will report an error during runtime.
Server Error TypeError: resolver is not a function This error happened while generating the page. Any console logs will be displayed in the terminal window.
When you export the GET function using the default keyword.
It will report errors during compilation, which is safer.
Type error: Route "src/app/helloworld/route.ts" does not match the required types of a Next.js Route. "GET" is not a valid Route export field.

Test Your API Using cURL

It’s always nice to test your API via cURL. This helps you test it right away without starting a HTTP client application.
curl https://localhost:3000/api/helloworld
The API should response JSON like this:
{ "message": "Hello World" }

How to Parse the NextRequest GET Query Parameter?

Parse Request Parameter in handler function

You can get the request parameter from the NextApiRequest object query property of type Partial<{[key: string]: string | string[];}. It allows you to get the parameter dynammically using key.
import { NextApiRequest, NextApiResponse } from 'next'; export default function handler(req: NextApiRequest, res: NextApiResponse) { const name = req.query.name as string; res.status(200).json({ message: `Well, Hello ${name}` }); }
You can get the name field from your request parameter as a query object key. This is possible because the req.query object type is Partial<{[key: string]: string | string[];}

Parse the Request Parameter in GET function

To parse a parameter in the GET function, you can extract the parameter from req.nextUrl.searchParam by calling the .get() method.
import { NextRequest, NextResponse } from 'next/server'; export async function GET(req: NextRequest) { const name = req.nextUrl.searchParams.get('name') as string; return NextResponse.json({ message: `Well, Hello ${name}` }}; }
The get method will return string | string[] | null so you need to cast it manually.

When Does the get method returns string?

The string value will be returned when you pass a scalar value as a parameter. It can be a number, boolean or string.

When Does the get method returns string[]?

When you pass array, then you will get value with return type string[]

When Does the get method returns null?

A null value is returned when there is no parameter with the name you ask.

Test Your New Parameterized API Using cURL

Now you can test the API using cURL like this:
curl "http://localhost:3000/api/helloworld?name=John"
The API should now respond with the name you supplied in the request parameter.
{ "message": "Well, Hello John" }

Adding Unit Tests for Parsing Query Parameters

Now that you've learned how to parse query parameters in your Next.js API routes, it's crucial to ensure that this functionality works correctly by adding unit tests.
Unit tests help verify that your code behaves as expected in isolation.
In this section, we'll walk through the process of creating unit tests for the query parameter parsing in your API routes.

Setting Up Your Testing Environment

Before you begin writing unit tests, make sure you have the necessary testing tools and dependencies installed.
We'll be using Jest, a popular JavaScript testing framework, for this example.
  1. Install Jest and related testing utilities if you haven't already:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
  1. Create a test file for your API route. In your project directory, create a new file named helloworld.test.ts in the same directory as your API route (api/helloworld.ts).

Writing handler Unit Tests

Now, let's write unit tests to verify that the query parameter parsing in your API route works correctly.
import { NextApiRequest, NextApiResponse } from 'next'; import handler from './helloworld'; describe('HelloWorld API', () => { it('should parse the name parameter correctly in the handler function', () => { const req = { query: { name: 'John', }, } as NextApiRequest; const res = { status: jest.fn(), json: jest.fn(), } as unknown as NextApiResponse; handler(req, res); expect(res.status).toHaveBeenCalledWith(200); expect(res.json).toHaveBeenCalledWith({ message: 'Well, Hello John' }); }); });
In the above code:
  • We create unit test case for the handler function.
  • For the test case, we create mock request and response objects to simulate the behavior of actual requests and responses.
  • We call the function with the mock request and response objects.
  • Finally, we use Jest's assertion methods (expect) to verify that the response matches our expectations.

Running the Tests

To run your unit tests, you can use the following command:
npm test
Jest will execute your tests and provide feedback on whether they pass or fail.
By adding unit tests for your query parameter parsing, you ensure that this critical functionality of your Next.js API route works as intended.
This helps catch potential issues early in the development process and provides confidence in the reliability of your code.

Conclusion

Parsing the request parameter in a REST API GET endpoint in Next.js is easy because the framework provides you with NextApiRequest or NextRequest, depending on your routing choice.
Always cast the returned value because it returns string | string[] | null.
Happy parsing parameters!
πŸ’‘
Hey, wasupp! Mozz knows that this article will help you in some way. But there are many use cases that may have been missed. Your feedback is very appreciated. Please add a comment below.

Discussion (0)

Related Posts