How to use URLSearchParams Web API (GET Method) In Next.js
JavaScript provides us a URLSearchParams Web API, by using it we can access the query params. It provides us a different methods such as forEach, get, getAll, has, values, keys to access the query string in a different ways. In our example, we are passing url string in a URL constructor which returns a URL object and by using that object we can access a URLSearchParams Web API.
Project Structure:
Example: The Below example demonstrate to access query params using URLSearchParams Web API (GET Method):
//File path: src/app/page.js
export default function Home() {
return (
<>
<form method="GET" action="api/submit">
<label>Name</label>
<input type="text"
placeholder="Enter Your Name"
name="name" required />
<br />
<label>Age</label>
<input type="text"
placeholder="Enter Your Age"
name="age" required />
<br />
<label>City</label>
<input type="text"
placeholder="Enter Your City"
name="city" required />
<br />
<button type="submit">Submit</button>
</form>
</>
);
}
//File path: src/app/api/submit/route.js
import { NextResponse } from "next/server";
export async function GET(req, res) {
const url = new URL(req.url);
const params = new URLSearchParams(url.search);
// Access individual query parameters
const name = params.get('name');
const age = params.get('age');
const city = params.get('city');
return new NextResponse(`
<h1>Submitted FormData:</h1>
<h2>Name: ${name}</h2>
<h2>Ag: ${age}</h2>
<h2>City: ${city}</h2>
`, {
status: 200,
headers: { 'content-type': 'text/html' }
})
}
Start your application using the command:
npm run dev
Output:
How To Get NextJS Query Params Serverside?
To access query parameters in Next.js on the server side, you can use the getServerSideProps
function. This function allows you to fetch data on each request, and it provides the context object which includes the query parameters. getServerSideProps function will work only on one Page router. You can also use different approaches such as FormData Web API, and URLSearchParams Web API to access the query params.
Table of Content
- Using getServerSideProps Function (Page Router)
- Using FormData Web API (POST Method)
- Using URLSearchParams Web API (GET Method)