Read Request Query Parameters in MSW

Share this video with your friends

Social Share Links

Send Tweet

Learn how to use the native URL and URLSearchParams classes to parse the intercepted request's URL and access its query parameters inside your Mock Service Worker handlers.

Lecturer: [0:05] Let's iterate on the movie recommendations so they exclude the movie we are currently browsing. First, in the source code, we will change the request URL for the recommended movies to include a query parameter named movieID. As its value, we will provide the ID of the current movie. This way we are letting the server know that we expect the recommendations for this particular movie.

[0:27] Next, let's reflect this change in the request handler. Although our request now has a query parameter in its URL, we should not put it in the request handler predicate. Remember that our handlers describe the server behavior. For the server, query parameters don't act as resource identifiers, instead, they represent additional data sent with the request, similar to the request body in that regard.

[0:45] To access query parameters, first, get the request reference from the resolver argument. The URL property on the request instance contains the resolved request URL including query parameters, represented as a plain string. Working with it in its raw form is inefficient, instead, let's construct a URL instance based on the request URL string.

[1:08] The URL class is a native JavaScript API that will parse the given URL and give us a handy interface to work with. To get the value of the movieID query parameter, we will type URL.searchParams.get and provide the parameter name movieID. The searchParams property on the URL instance represents parsed query parameters, and its get method returns the value of a parameter by its name.

[1:39] Knowing the exact movie ID, let's now filter it out from the list of recommended movies and update the mock response.

[1:50] Our recommendations handler now matches the behavior we would expect from the production API much more closely.