URL Parameters & Query Strings - Next.js
Next.js does URL parameters and query strings a little differently - and a little differently depending on whether you're using client or server components.
1import Link from "next/link";
2
3export default async function EuroArticle({
4 params,
5 searchParams
6 }: {
7 params: Promise<{articleId: string }>;
8 searchParams: Promise<{lang?: "en" | "fr" | "de"}>
9 })
10 {
11 const {articleId} = await params;
12 const {lang = "en"} = await searchParams;
13
14 return (
15 <div>
16 <h2>Euro Article {articleId}</h2>
17 <p>Current Language: {lang}</p>
18
19 <div>
20 <Link href={`/articles/&dollar{articleId}?lang=en`}>English</Link>
21 <Link href={`/articles/&dollar{articleId}?lang=fr`}>French</Link>
22 <Link href={`/articles/&dollar{articleId}?lang=de`}>German</Link>
23 </div>
24 </div>
25 );
26}
27//Replace ` with a backtick character, &dollar with a dollar character.
The code above is the server side flavor of extracting the params and searchParams values into your code.
1"use client"
2import Link from "next/link";
3import { use } from "react";
4
5export default function EuroArticle({
6 params,
7 searchParams
8 }: {
9 params: Promise<{articleId: string }>;
10 searchParams: Promise<{lang?: "en" | "fr" | "de"}>
11 })
12 {
13 const {articleId} = use(params);
14 const {lang = "en"} = use(searchParams);
15
16 return (
17 <div>
18 <h2>Euro Article {articleId}</h2>
19 <p>Current Language: {lang}</p>
20
21 <div>
22 <Link href={`/articles/&dollar{articleId}?lang=en`}>English</Link>
23 <Link href={`/articles/&dollar{articleId}?lang=fr`}>French</Link>
24 <Link href={`/articles/&dollar{articleId}?lang=de`}>German</Link>
25 </div>
26 </div>
27 );
28}
29//Replace ` with a backtick character, &dollar with a dollar character.
The code above is the client side flavor of extracting the params and searchParams values into your code. There's no async/await since it's a client component, so instead you'll use the use hook. Use this URL to view the page results on your local machine: localhost:3000/articles/euroArticle?lang=en
Summary: Make a new Next.js directory, create a new page.tsx file into that directory and copy/paste each of the above files (swap them out or create a second directory to handle both of them). This pseudo code will display 3 links on your page (English French German) representing the language for each article. The articleId is what Next.js refers to as the params value - actually what you know as the page name in the url (left of the "?" character). The searchParams are name/value pairs to the right of the "?" character.