키모스토리

#23. URL Query Parameters 본문

Web Devlopment/NextJs

#23. URL Query Parameters

키모형 2025. 12. 29. 14:47
반응형

URL Query Parameters

GET 요청시 검색처리 (url query parameters)

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const query = searchParams.get("query");
  const filteredComments = query
    ? comments.filter((comment) => comment.text.includes(query))
    : comments;
  return Response.json(filteredComments);
}

 

GET 요청 방법 (?query=검색어)

http://localhost:3000/comments?query=first

 

응답

[
  {
    "id": 1,
    "text": "This is the first comment"
  }
]

 

1) request.nextUrl는 무엇인가요?

Route Handler의 GET(request)에 들어오는 request를 NextRequest 타입으로 받으면, Next.js가 표준 Request에 추가 기능을 얹어 둔 객체를 전달해 줍니다. Next.js+1

그 중 핵심이 request.nextUrl인데요.

  • request.nextUrl은 표준 URL 객체를 확장한 “NextURL” 입니다.
  • 즉, URL을 직접 파싱(new URL(request.url))하지 않아도, Next.js가 이미 파싱해 둔 값을 안전하게 꺼내 쓰실 수 있습니다. Next.js+1

예를 들어,

request.nextUrl.pathname      // "/comments"
request.nextUrl.searchParams  // URLSearchParams 객체

처럼 접근합니다. nextjs-ko.org+1


2) request.nextUrl.searchParams는 무엇인가요?

searchParams는 브라우저에서도 동일하게 쓰는 URLSearchParams 인터페이스입니다.

즉, 아래처럼 쿼리스트링(?key=value)을 다루는 용도입니다.

  • get(key) : 단일 값 1개 가져오기(없으면 null)
  • getAll(key) : 같은 키가 여러 번 들어온 경우 전체 배열로 받기
  • has(key) : 존재 여부
  • entries() / forEach() : 전체 순회

예:

const searchParams = request.nextUrl.searchParams;

searchParams.get("query");      // "first" (없으면 null)
searchParams.has("query");      // true/false
searchParams.getAll("tag");     // ["a","b"]  (예: ?tag=a&tag=b)
const searchParams = request.nextUrl.searchParams; searchParams.get("query"); // "first" (없으면 null) searchParams.has("query"); // true/false searchParams.getAll("tag"); // ["a","b"] (예: ?tag=a&tag=b)

또한 URL 인코딩이 되어 있으면 자동으로 디코딩된 값을 받습니다.

  • /comments?query=first%20comment → get("query")는 "first comment"로 반환

3) “Query Params”와 “Path Params”는 완전히 다릅니다

여기서 자주 혼동하시는 부분이 있는데요.

  • searchParams는 ?query=... 같은 URL Query Params만 다룹니다.
  • /comments/[id] 같은 Path Params는 Route Handler의 두 번째 인자에서 받습니다.

예)

// /comments/3  → params.id = "3"
// /comments?query=first → searchParams.get("query") = "first"
 

4) 질문 주신 코드 예제 + 보완 포인트

질문 주신 코드는 아래와 같습니다.

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const query = searchParams.get("query");
  const filteredComments = query
    ? comments.filter((comment) => comment.text.includes(query))
    : comments;
  return Response.json(filteredComments);
}

여기서 실무적으로 자주 추가하는 보완 포인트는 아래 2가지입니다.

(1) 공백/대소문자 처리

includes()는 기본적으로 대소문자 구분을 합니다. 또한 query에 공백이 들어오면 의도치 않게 필터가 안 될 수 있습니다.

const raw = searchParams.get("query");
const query = raw?.trim();

const filtered = query
  ? comments.filter((c) =>
      c.text.toLowerCase().includes(query.toLowerCase())
    )
  : comments;
(2) NextResponse.json으로 통일(권장)

Route Handler에서는 Response.json()도 되지만, Next.js 스타일로는 NextResponse.json()을 많이 사용합니다.


5) 최종 예시 코드 (검색 Query 적용)

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

export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;

  const query = searchParams.get("query")?.trim();

  const filteredComments = query
    ? comments.filter((c) =>
        c.text.toLowerCase().includes(query.toLowerCase())
      )
    : comments;

  return NextResponse.json(filteredComments);
}

호출 예:

  • http://localhost:3000/comments?query=first

응답 예:

[
  { "id": 1, "text": "This is the first comment" }
]

 

6) 참고: 같은 키가 여러 번 오는 경우(getAll) 예시

URL:

  • /comments?tag=a&tag=b&tag=c

코드:

const tags = request.nextUrl.searchParams.getAll("tag");
// ["a","b","c"]
 
이 패턴은 “필터가 여러 개 적용되는 검색”을 구현할 때 매우 유용합니다.

 

반응형

'Web Devlopment > NextJs' 카테고리의 다른 글

#22. Route Handlers  (0) 2025.12.29
#20. Parallel Routes  (0) 2025.12.28
#19. Error Handling 실전  (0) 2025.12.28
#18. Loading UI , Error Handling  (0) 2025.12.28
#17. Templates (vs layout)  (0) 2025.12.28