Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get url params in API route handler in Next.js

I have a client component GetUserInfoButton. In that component, I send a GET request on url http://localhost:3000/test/users/[id] where [id] is a MongoDb-like alphanumeric sequence.

Inside app/api/users/[id]/route.ts, I want to receive that request and work with that [id]. Here's my GetUserInfoButton component:

'use client';

export default function GetUserInfoButton({ id }: { id: string }) {
    const contentType = "application/json";
    const handleClick = async (id: string) => {
        try {
            const res = await fetch(`/api/users/${id}`, {
                method: "GET",
                headers: {
                    "Content-Type": contentType,
                }
            });
            if (!res.ok) {
                throw new Error(res.status.toString());
            }
        } catch (error) {
            console.log("error ===> ", error);
        }
    };

    return (
        <button onClick={() => handleClick(id)}>
            Get
        </button>
    );
}

Here's my route.ts file:

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

export async function GET(req: NextRequest) {
    const id = req.url.split("http://localhost:3000/api/users/")[1];
    return NextResponse.json({
        success: true,
        id: id
    }, {
        status: 200,
    })
}

Back when it was the pages router, I could use useRouter() on the client and get id on the server like this: const { query: { id } } = req.

How do I get id params in server component?

I'm using Next.js 13.4.16.

like image 827
in43sh Avatar asked Feb 17 '26 00:02

in43sh


1 Answers

In the app directory, when you are in a dynamic route (aka the [id] folders), your API route handler gets passed a second object parameter which will hold your slug, as the doc shows:

Next.js ^15.0.0 with TypeScript:

// app/items/[slug]/route.ts

export async function GET(
  request: Request,
  { params }: { params: Promise<{ slug: string }> }
) {
  const slug = (await params).slug;
  console.log(slug); // 'a', 'b', or 'c'
}

Next.js ^15.0.0 with JavaScript:

// app/items/[slug]/route.js

export async function GET(request, { params }) {
  const slug = (await params).slug;
  console.log(slug); // 'a', 'b', or 'c'
}

Next.js >=13.0.0 & <15.0.0 with TypeScript:

// app/api/users/[id]/route.ts

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

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  console.log(params.id);
  return NextResponse.json({ msg: "Hello World" });
}

Next.js >=13.0.0 & <15.0.0 with JavaScript:

// app/api/users/[id]/route.js

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

export async function GET(req, { params }) {
  console.log(params.id);
  return NextResponse.json({ msg: "Hello World" });
}

For future readers, you can get query strings (aka the ?search=value) in Next.js >=13.0.0 & <15.0.0 with JavaScript this way:

import { NextResponse } from "next/server";

export async function GET(req) {
  const { searchParams } = new URL(req.url);
  console.log(searchParams.get("search"));
  return NextResponse.json({ msg: "Hello World" });
}

And in Next.js ^15.0.0 with JavaScript:

export function GET(request) {
  const searchParams = request.nextUrl.searchParams
  const query = searchParams.get('query')
  // query is "hello" for /api/search?query=hello
}
like image 200
yousoumar Avatar answered Feb 19 '26 14:02

yousoumar