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'23const worker = setupWorker(4 rest.get('/products', (req, res, ctx) => {5 const productId = req.url.searchParams.get('id')67 return res(8 ctx.json({9 productId,10 }),11 )12 }),13)1415worker.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'23const worker = setupWorker(4 rest.get('/products', (req, res, ctx) => {5 const productIds = req.url.searchParams.getAll('id')67 return res(8 ctx.json({9 productIds,10 }),11 )12 }),13)1415worker.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}