Skip to content
next

Next.js: Get query parameters

Mar 8, 2023Abhishek EH1 Min Read
Next.js: Get query parameters

In this article, we will see how to get query parameters in Next.js

Project setup

Create a new Next.js app using the following command:

1npx create-next-app nextjs-query-parameters

In Next.js the routing comes in build. We don't have to install any packages to do so.

There are different ways in which we can access query parameters on the client side and on the server side.

Server side

If you want to access query parameters inside the getServerSideProps function, you can do so by using the following code:

1export async function getServerSideProps(context) {
2 console.log({ query: context.query })
3 return {
4 props: {},
5 }
6}

Now if you access http://localhost:3000/?a=1, you will see { query: { a: '1' } } printed in the terminal.

Client side

If you want to access query parameters on the client side, you can make use of the useRouter hook.

1import { useRouter } from "next/router"
2
3export async function getServerSideProps(context) {
4 console.log({ query: context.query })
5 return {
6 props: {},
7 }
8}
9export default function Home() {
10 const router = useRouter()
11 console.log({ query: router.query }) // 👉 {"query":{"a":"1"}}
12 return <></>
13}

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2023 CodingDeft.Com