Next.js Discord

Discord Forum

searchParams are not working

Unanswered
Yellowfin tuna posted this in #help-forum
Open in Discord
Yellowfin tunaOP
export async function GET(req: NextRequest) {
    try {
        const searchParams = req.nextUrl.searchParams;

        const condition = searchParams.get("condition")

        console.log(condition)
    } catch (error) {
        console.error('GET_PRODUCTS', error);
        return new NextResponse('Internal error', { status: 500 });
    }
} 
in console am getting undefined but this is url am currently on ".../electronics?condition=used" why I can't get value of condition?

18 Replies

Toyger
Is that an API function?

How are you calling it?
searchParams is an object so you should access values using the dot notation (req.nextUrl.searchParams.condition).

[From the docs](https://nextjs.org/docs/app/api-reference/functions/next-request#nexturl):
// Given a request to /home?name=lee, searchParams is { 'name': 'lee' }
request.nextUrl.searchParams
@Toyger Is that an API function? How are you calling it?
Yellowfin tunaOP
yeah
export async function GET(req: NextRequest) {
    try {
        const condition = req.nextUrl.searchParams.condition;

        console.log(condition)
    } catch (error) {
        console.error('GET_PRODUCTS', error);
        return new NextResponse('Internal error', { status: 500 });
    }
} 
error:
Property 'condition' does not exist on type 'URLSearchParams'.ts(2339)
any
and am still on
http://localhost:3000/products/electronics?condition=used
url
and this is weird
export async function GET(req: NextRequest) {
    try {
        const url = new URL(req.url);

        console.log(url)
    } catch (error) {
        console.error('GET_PRODUCTS', error);
        return new NextResponse('Internal error', { status: 500 });
    }
}
when I console url it returns this :
URL {
  href: 'http://localhost:3000/api/products',
  origin: 'http://localhost:3000',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:3000',
  hostname: 'localhost',
  port: '3000',
  pathname: '/api/products',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
I guess in URL href should be
http://localhost:3000/products/electronics?condition=used
instead of
http://localhost:3000/api/products
am really confused right now.
And doing it like this still returns null?

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const condition = searchParams.get('condition')

  // ...
}
am stuck here all day trying various things but nothing seems to work...
For some reason your search params are getting removed from the url in the request object...
Yellowfin tunaOP
omg am retarded, I didn't pass params to my api
my bad bro :lolsob:
that's hilarious, but it happens to everyone sooner or later 😂