Guides & Tutorials
How to test serverless functions locally
Throughout December we'll be highlighting a different Netlify feature each day. It might just be the thing you need to unlock those creative juices, and dust off that domain you registered but never deployed! Keep an eye on the blog and on Twitter for each feature!
Yesterday we saw that you could deploy serverless functions by adding your JavaScript, TypeScript or Go files to a specified folder in your project. But how do you develop and test your functions locally so that you can validate that they work correctly before deploying them?
Netlify CLI has the answer in the form of Netlify Dev.
One of the advantages of using Netlify Dev (which comes bundled as part of Netlify CLI), is that it will detect the serverless functions in your project, and automatically serve them for you in a local development server so that they behave just the same as when they are deployed to Netlify.
Simply run netlify dev
in your project directory. Your functions will have access to your project's environment variables and be served on the same port as the rest of your web project.
Tip: Install Netlify CLI first by running
npm install -g netlify-cli
But there's more!
Netlify CLI can also help you with other tasks related to building serverless functions including testing invocations and creating new functions from a set of boilerplate examples in JavaScript, TypeScript and Go.
Try running netlify functions:create
in your project folder and following the prompts.
You can also explore the functions command in Netlify CL by running netlify help functions
# netlify help functions
COMMANDS
functions:build Build functions locally
functions:create Create a new function locally
functions:invoke Trigger a function while in netlify dev with simulated data, good for testing function calls including Netlify's Event Triggered Functions
functions:list List functions that exist locally
functions:serve (Beta) Serve functions locally