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

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, with might use query string values to dynamically render a part of the user interface with specific parameters, that the users can save as bookmarks, and restore later.

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

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

timeFormat=24h
timezones=Europe/London,Europe/Nicosia
Europe/Rome=luca
Europe/London=lars,erik,john

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}</>
}

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

URLsearchParams.has(”timeFormat”)
/embedfalse
/embed?timeFormat=24htrue

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']}</>
}

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 }
  );
}

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.