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.
Using getServerSideProps Function (Page Router)Next.js provides the use of a getServerSideProps Function, which will allow us to fetch data from the server. It accepts the context object as a parameter, which allows us to access query, req, etc..
Steps to Setup a NextJS AppStep 1: Create a NextJS application using the following command and answer a few questions.
npx create-next-app@latest app_name Step 2: It will ask you some questions, so choose as the following.
Make sure you choose a Pages Router.
√ Would you like to use TypeScript? ... No √ Would you like to use ESLint? ... Yes √ Would you like to use Tailwind CSS? ... No √ Would you like to use `src/` directory? ... Yes √ Would you like to use App Router? ... No √ Would you like to customize the default import alias (@/*)? ... No Step 3: After creating your project folder, move to it using the following command.
cd app_name Project Structure: Example: The below example demonstrate to get the query params at server side using getServerSideProps Function (Pages Router).
Note: Remove the included CSS file from the _app.js.
JavaScript
//File path: src/pages/index.js
export default function Home() {
return (
<>
<form method="GET" action="/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>
</>
);
}
JavaScript
//File path: src/pages/submit.js
export default function Page({ name, age, city }) {
return (
<>
<h1>Submitted data</h1>
<p><strong>Name:</strong> {name}</p>
<p><strong>Age:</strong> {age}</p>
<p><strong>City:</strong> {city}</p>
</>
);
}
// This function runs on the server side and fetches query parameters
export async function getServerSideProps(context) {
const { query } = context;
// Extracting the parameters from the query object
const { name, age, city } = query;
// Pass the parameters to the page component as props
return {
props: {
name,
age,
city,
},
};
}
Start your application using the command:
npm run dev Output:
Using FormData Web API (POST Method)JavaScript provides us a FormData Web API, by using it we can access the form data values. FormData represents the object, which contains the form data in the form of a key/value. key is the name attribute of the input field and Value represents the value of the input field.
Steps to Setup a NextJS AppStep 1: Create a NextJS application using the following command and answer a few questions.
npx create-next-app@latest app_name Step 2: It will ask you some questions, so choose as the following.
√ Would you like to use TypeScript? ... No √ Would you like to use ESLint? ... Yes √ Would you like to use Tailwind CSS? ... No √ Would you like to use `src/` directory? ... Yes √ Would you like to use App Router? ... Yes √ Would you like to customize the default import alias (@/*)? ... No Step 3: After creating your project folder, move to it using the following command.
cd app_name Project Structure:
Example: The below example demonstrate to get the query params at server side using FormData API (POST Method).
Note: Remove the included CSS file from the layout.js
JavaScript
//File path: src/app/page.js
export default function Home() {
return (
<>
<form method="POST" 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>
</>
);
}
JavaScript
//File path: src/app/api/submit/route.js
import { NextResponse } from "next/server";
export async function POST(req, res) {
const formData = await req.formData()
const name = formData.get('name');
const age = formData.get('age');
const city = formData.get('city');
console.log(formData)
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:
Using URLSearchParams Web API (GET Method)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):
JavaScript
//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>
</>
);
}
JavaScript
//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:
|