Get url params in API route handler in Next.js

in4*_*3sh 5 javascript 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>
    );
}
Run Code Online (Sandbox Code Playgroud)

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,
    })
}
Run Code Online (Sandbox Code Playgroud)

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.

You*_*mar 9

在目录中app,当您处于动态路由(也称为[id]文件夹)中时,您的 API 路由处理程序将传递第二个对象参数,该参数将保存您的 slug,如文档所示:

// 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" });
}
Run Code Online (Sandbox Code Playgroud)

这是没有类型的版本:

// 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" });
}
Run Code Online (Sandbox Code Playgroud)

对于未来的读者,您可以通过以下方式获取查询字符串(也称为?search=value):

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" });
}
Run Code Online (Sandbox Code Playgroud)