How to set up serverless functions on Netlify
This is a step-by-step walkthrough on how to set up serverless functions through Netlify in less than 10 minutes. You can add serverless functions to an existing Netlify site (for instance, a Jekyll, Gatsby, or plain HTML site) or create a brand new project whose sole purpose is to be a serverless repository. To start, just navigate to your project's root directory. Then, do the following.
Serverless setup process
-
Run
npm init -y
if you don't already have a package.json -
Add a .gitignore file to the root of your project. Inside of this file, add two lines:
node_modules functions
-
Add a netlify.toml file to the root of your project, and inside:
[build] functions = "lambda"
-
Run
npm i netlify-lambda
-
Run
npm i axios
if you want to makeGET
/POST
/etc. requests from your serverless function -
Add these scripts to your package.json:
// ... "scripts": { "lambda-serve": "netlify-lambda serve functions", "lambda-build": "netlify-lambda build functions" }, // ...
-
Create a folder called functions in the root of your project
-
Inside it, create a file called foobar.js. The name of this file will be the name of your endpoint. Netlify will pass in the
event
andcontext
for you; you'll want to call thecallback
function to return data to your user. Here's the bare minimum of what you need:exports.handler = function(event, context, callback) { callback(null, { statusCode: 200, body: "Success!" }) }
As soon as that function gets hit, it returns "Success!" which is probably a little too simple. So here's a more realistic example of performing a
GET
request to some API and returning the data. You could just as easily use aPOST
request:// We can use axios to perform GET requests const axios = require('axios') exports.handler = function(event, context, callback) { // This is for sending a response back to the user; these headers allow access // from any URL which will prevent CORS errors, but you can scope this to your // application if you'd prefer. const sendDataToUser = body => { callback(null, { statusCode: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept' }, body: JSON.stringify(body) }) } // This performs and API call then sends the data back to the user const getDataFromAPI = () => { axios .get('http://dummy.restapiexample.com/api/v1/employees') .then(res => sendDataToUser(res.data)) .catch(err => sendDataToUser(err)) } // This makes sure this is a GET request, then runs the function if (event.httpMethod === 'GET') { getDataFromAPI() } }
-
To test this, run
npm run lambda-serve
to spin up a local server. You'll want to send a request to http://localhost:9000/foobar with a tool like Insomnia or Postman – or make the request from a client-side app like so:fetch('http://localhost:9000/foobar') .then(data => console.log(data)) .catch(error => console.log(error))
-
When you're ready to go live, run
npm run lambda-build
. This will build your functions/foobar.js file to lambda/foobar.js. Push to Netlify and you'll be able to access your function at you.com/.netlify/functions/foobar.
Does this work with Jekyll/Gatsby/etc.?
Yes, you can bake serverless functions into any existing Netlify project. Or you can make it a standalone project if you don't want it connected to another site – I think in this case, you'd just need an index.html
(which could be blank) and the files from the walkthrough above.
How do I add more serverless functions?
To create a new serverless function, just create a new file in the functions folder. I recommend using a descriptive name to keep yourself organized.
Do I need to do anything special in the Netlify dashboard to activate serverless functions?
Nope, that's why we have the netlify.toml file. Build your site as usual – just make sure to add that file to your project.
What's a good use case for serverless functions?
There are a few. Personally, if I needed a whole set of REST actions I'd probably stick to a framework like Rails, but sometimes I just need to process a one-off payment, validate a license against an API, etc. I don't always want to manage a server or pay a monthly cost just for that one function, so serverless is really nice for that.
How does naming work?
The name of your file becomes the name of your endpoint. For instance, a file at functions/foobar.js will create an endpoint at localhost:9000/foobar in dev and you.com/.netlify/functions/foobar in prod.
Why Netlify and not something like AWS?
Netlify's UI is nicer and if you already have projects with them, it's nice to keep everything in one place. They're also free for up to 125,000 requests per month.