DEV Community

Cover image for Query string params in Next.js (14) with App Router
Luca Restagno
Luca Restagno

Posted on • Originally published at shipped.club

8 2 2 2 1

Query string params in Next.js (14) with App Router

The query string is a part of the URL (Uniform Resource Locator) that assigns values to specific parameters.

While developing our web apps, we might use query string values to dynamically render a part of the user interface with specific parameters.

For instance, I provide a shareable link with the Timezone Checker web app, including the user configuration.

https://timezonechecker.app/embed?timeFormat=24h&timezones=Europe/London,Europe/Nicosia&Europe/Rome=luca&Europe/London=lars,erik,john
Enter fullscreen mode Exit fullscreen mode

The query string parameters and values are (parameter=value):

timeFormat=24h
timezones=Europe/London,Europe/Nicosia
Europe/Rome=luca
Europe/London=lars,erik,john
Enter fullscreen mode Exit fullscreen mode

In Next.js with App Router, there are different components: client components, pages, layouts, and routes.
Let’s see how we can read the query strings in each one of those.

Client components

In a client component you can use the React Hooks useSearchParams to return a read only version of the URLSearchParams JavaScript interface.

'use client'

import { useSearchParams } from 'next/navigation'

export default function SearchBar() {
  const searchParams = useSearchParams()

  const timeFormat = searchParams.get('timeFormat')

  // URL -> `/embed?timeFormat=24h`
  // `timeFormat` -> '24h'
  return <>Time format: {timeFormat}</>
}
Enter fullscreen mode Exit fullscreen mode

You can use the URLSearchParams method has() to determine if a query string param is present or not.

URL searchParams.has(”timeFormat”)
/embed false
/embed?timeFormat=24h true

The URLSearchParams interface has other read-only methods, like getAll(), keys(), values(), entries(), forEach(), and toString().

Pages

In pages, you can use the searchParams prop to access the query string params.

In this case, an object is returned.


export default function EmbedPage({ searchParams }) {
  // URL -> `/embed?timeFormat=24h`
  // searchParams['timeFormat'] -> '24h'
  return <>Time format: {searchParams['timeFormat']}</>
}
Enter fullscreen mode Exit fullscreen mode

Routes

In routes (backend endpoints), you can access the URLSearchParams interface this way:


import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {

    // URL -> `/api/embed?timeFormat=24h`

  const timeFormat = req.nextUrl.searchParams.get("timeFormat")

  return NextResponse.json(
    { timeFormat },
    { status: 200 }
  );
}
Enter fullscreen mode Exit fullscreen mode

Layouts

In layouts, you cannot access the query string params. Instead, access them from the pages or client components, rendered inside the layout.

Conclusion

Query strings are the comfortable way to save and transmit data into the URL, to allow the users to easily share configurations via the URL, and send data from the client to the server.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
egolegegit profile image
egolegegit

Simple and to the point! Thank you!

Collapse
 
ikoichi profile image
Luca Restagno

Thanks @egolegegit 😄

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay