How to test Netlify Functions locally

I have quite a few sites hosted on Netlify, and some of them use a feature called Netlify Functions.

This is probably - of course after the incredible static hosting service they provide - my favorite feature.

You add a JavaScript file with an exported function to handle the request to the URL, and you’re set.

You can do pretty much anything and I use them as little utilities to visualize internal data I need or to perform operations that “connect the dots” aka glue different tools I use to run my business.

If you want to learn more about them, check out my Netlify Functions tutorial.

In this post I want to talk in particular about how to test Netlify functions locally.

I had this need the other day when I wanted to do a change to a Netlify Function that was live running to handle signups to my Bootcamp and I didn’t want to disrupt my operations, causing problems to a customer.

I did test this “live” prior to opening signups to see if things were running as expected, but now I had a different need.

So here’s what I did.

I first installed the Netlify CLI

npm install -g netlify-cli

Then from the website folder I ran

netlify functions:serve

This served the serverless functions locally, on port 9999 so I just had to reach them using a URL like

http://localhost:9999/.netlify/functions/<name>

and I was able to test them by faking a POST request using Insomnia.

In this way deploying the changes to production was much less stressful.

This way of testing the functions also grabs any Netlify environment variables you might have set in the Netlify Dashboard, so it just works like you were running it on Netlify.