Query params in Next.js (14) with App Router for client and server side
August 6th 2024
With the App Router in Next.js, we use a different approach to define routes and handle query parameters. Here’s how to handle query parameters with the App Router in Next.js:
1. Client-Side Query Parameters
With the App Router, you can still use the useRouter hook from next/router to access query parameters on the client-side.
// app/client/page.js
"use client";
import { useRouter } from 'next/router';
const ClientPage = () => {
const router = useRouter();
const { param1, param2 } = router.query; // Access query parameters
return (
<div>
<h1>Client-Side Query Params</h1>
<p>Param1: {param1}</p>
<p>Param2: {param2}</p>
</div>
);
};
export default ClientPage;
2. Server-Side Query Parameters
For server-side rendering (SSR) or static generation in the App Router, you can access query parameters in the layout or page components using headers or searchParams.
Example with Server Component:
// app/server/page.js
export default async function ServerPage({ searchParams }) {
const { param1, param2 } = searchParams;
return (
<div>
<h1>Server-Side Query Params</h1>
<p>Param1: {param1}</p>
<p>Param2: {param2}</p>
</div>
);
}
3. API Routes
For the full string use the url and/or pull the request parameters from that url using .get
.
import { NextRequest } from 'next/server'
export async function GET(req: NextRequest) {
const reqUrl = req.url
const { searchParams } = new URL(reqUrl)
console.log(searchParams.get("param1")) // should print lorem
}
Usage
To see the different contexts in action, you can navigate to the following URLs:
• Client-Side: http://localhost:3000/client?param1=value1¶m2=value2
• Server-Side: http://localhost:3000/server?param1=value1¶m2=value2
• API Route: http://localhost:3000/api/query?param1=value1¶m2=value2
This setup allows you to parse and use query parameters in a Next.js application using the App Router on the client-side, server-side, and in API routes.