javascriptnext.js

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.


Solution

  • 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:

    TypeScript (Next.js ^15.0.0)

    // app/api/users/[id]/route.ts
    
    import { NextRequest, NextResponse } from "next/server";
    
    export async function GET(req: NextRequest, { params }:  { params: Promise<{ id: string }> }) {
      const { id } = await params;
      console.log(id);
      return NextResponse.json({ msg: "Hello World" });
    }
    

    TypeScript (Next.js <15.0.0)

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

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