Read a Query Parameter
Easy · Route Handlers
A route handler receives the incoming Request. To read the query string (the part after ?), create a URL object from request.url and use its searchParams: new URL(request.url).searchParams.get("name"). (Next.js also has NextRequest, which extends Request and adds a ready-made request.nextUrl; the plain Web Request is used here.)
Implement GET in app/api/greet/route.ts:
- /api/greet?name=Ana returns the JSON { message: "Hello, Ana!" }
- if name is missing or empty, return { message: "Hello, stranger!" }
The driver greet(query) is already written: it sends a request with the given query string and returns { status, body }.
Next: Read the Search Query