⚡ serverless functions with netlify cli
The other day I read a tweet from James Quick which asked a question that I definitely had some input on.
What do you think the easiest way is to write and run a Hello World #serverless function?! For me, it's using @Netlify and running `netlify dev`.
— James Q Quick (@jamesqquick) April 27, 2020
He's right, netlify dev
is the best way to run your serverless functions locally. But did you know that the Netlify CLI can scaffold out functions for you based on a bunch of different templates? Let me walk you through it.
First, you're going to want to install the command line tool globally. And if that's not your style, you can always run it with npx
.
Next, create a directory for your project, I called mine bg-serverless
, and create a netlify.toml
file in there. The functions
property tells Netlify where to find and create your serverless functions.
Now let's use Netlify CLI to create a serverless function for us. Enter the command below and notice how you are prompted to choose from one of many different serverless function templates!
You'll see that Netlify created a hello
directory inside of the functions
folder, containing a handler function which returns a response object. This is the most basic of serverless functions, but Netlify also has templates for a GraphQL server, Stripe payments, FaunaDB operations, and Sanity integrations!
Run netlify dev
to serve your functions locally at /.netlify/functions/hello
. But typing this URL sucks, so let's define a redirect in netlify.toml
to simplify the endpoint.
Now we can hit /api/hello
instead of the ugly default Netlify URL.
Let's make this site live! Use the Netlify CLI one more time to create a site, and deploy your serverless functions.
If you learn best from watching instead of reading, here is the video version of this post.
Now you're all set to build some awesome things using serverless functions! Hit me up @bradgarropy on Twitter and show me what you create!