Skip to content

How can i use querystring parameters with msw mock api responses? #28459

Closed Answered by kasperpeulen
OwenPattison asked this question in Help
Discussion options

You must be logged in to vote

https://mswjs.io/docs/recipes/query-parameters/

export const handlers = [
  http.get('/product', ({ request }) => {
    // Construct a URL instance out of the intercepted request.
    const url = new URL(request.url)
 
    // Read the "id" URL query parameter using the "URLSearchParams" API.
    // Given "/product?id=1", "productId" will equal "1".
    const productId = url.searchParams.get('id')
 
    // Note that query parameters are potentially undefined.
    // Make sure to account for that in your handlers.
    if (!productId) {
      return new HttpResponse(null, { status: 404 })
    }
 
    return HttpResponse.json({ productId })
  }),
]

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by OwenPattison
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants