LOGOMock Service Worker
  1. Recipes
  2. Query parameters

Query parameters

In order to access a query parameter of the intercepted request, use the searchParams property on the req.url instance. The value of that property is a URLSearchParams instance that contains all query parameters.

Examples

Single parameter

1import { setupWorker, rest } from 'msw'
2
3const worker = setupWorker(
4 rest.get('/products', (req, res, ctx) => {
5 const productId = req.url.searchParams.get('id')
6
7 return res(
8 ctx.json({
9 productId,
10 }),
11 )
12 }),
13)
14
15worker.start()

Request

GET/products?id=123

Response

200OK
Body
1{
2 // Where '123' is the value of `req.url.searchParams.get('id')`
3 // parsed from the request URL.
4 "productId": "123"
5}

Multiple parameters

Call req.url.searchParams.getAll() method to access all values assigned to a parameter.

1import { setupWorker, rest } from 'msw'
2
3const worker = setupWorker(
4 rest.get('/products', (req, res, ctx) => {
5 const productIds = req.url.searchParams.getAll('id')
6
7 return res(
8 ctx.json({
9 productIds,
10 }),
11 )
12 }),
13)
14
15worker.start()

Read more in the URLSearchParams.getAll() specification.

Request

GET/products?id=1&id=2&id=3

Response

200OK
Body
1{
2 "productIds": ["1", "2", "3"]
3}