Serverless functions really start to show their potential when we can accept user input and respond to it. The most straightforward way to do this is with query parameters in the browser using
GET requests. In this article, we’ll look at how to retrieve query parameters in a serverless function and use them to affect the output of our function.
Create your dev environment
Write the serverless function
To start, let’s create a serverless function that will allow us to boop our friends. Create a file called
boop-a-friend.js in the
functions folder of your project and write the following code inside:
netlify dev and visit
http://localhost:9999/.netlify/functions/boop-a-friend and we see the return text, “You booped Jason on the nose. Boop!”
We want to be able to choose who we boop, though, and we want to do that from the browser — meaning we’ll be using the
GET method to call our serverless function. In practice, it will look like this:
We’re using a query string (the
?boopee=Marisa part) to set our
boopee value to “Marisa”, because that’s who we want to boop.
Next, we need to use the query string value in our serverless function.
Retrieve values from query strings in serverless functions
Because we’re using Netlify Functions, we receive the
event as the first argument to our serverless function, and it contains a property called
queryStringParameters, which contains any query string values as an object.
What this looks like in practice is that if we call our serverless function using the query string above:
We can access query parameters in our serverless function by making the following changes:
When we run
netlify dev and call our function, the logs will show us the following output:
boopee is there!
Now we can use it by making a few more adjustments to our code:
Now we can call our function by visiting
http://localhost:9999/.netlify/functions/boop-a-friend?boopee=Marisa and we’ll see that we’re booping Marisa, just like we wanted to!
If we don’t add a query string, we fall back to the default text:
We did it! We can now send, parse, and use query string parameters in our serverless functions!