最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get url params in API route handler in Next.js - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Aug 25, 2023 at 8:42 Youssouf Oumar 45.9k16 gold badges100 silver badges104 bronze badges asked Aug 25, 2023 at 4:46 in43shin43sh 9212 gold badges14 silver badges37 bronze badges 1
  • 1 You should be able to access it through the params prop, as it is described here in the documentation. – Geshode Commented Aug 25, 2023 at 5:17
Add a comment  | 

1 Answer 1

Reset to default 27

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
}
发布评论

评论列表(0)

  1. 暂无评论