How to test Netlify Functions locally

By

Test Netlify Functions locally with the Netlify CLI: run netlify functions:serve or netlify dev, hit them on port 9999, and use your environment variables.

~~~

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

If you’d rather not install it globally, add it to the project with npm install --save-dev netlify-cli and call netlify from an npm script. Netlify recommends that for CI.

Then from the website folder I ran

netlify functions:serve

This served the 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.

If you want the whole site running locally (static files, redirects, and functions together), run netlify dev instead. functions:serve is enough when you only care about the functions.

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.

Tagged: Services · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about services: