Frontend Developers: I'm redesigning DevTools. Want early access?

Serverless Netlify functions in 10 minutes

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.

1. Run npm init -y if you don’t already have a package.json

2. Add a .gitignore file to the root of your project and add this to it:

node_modules
functions

3. Add a netlify.toml file to the root of your project, and inside:

[build]
  functions = "lambda"

4. Run npm i netlify-lambda

5. Run npm i axios if you want to make GET/POST/etc. requests from your serverless function

6. Add these scripts to your package.json:

// ...
"scripts": {
  "lambda-serve": "netlify-lambda serve functions",
  "lambda-build": "netlify-lambda build functions"
},
// ...

7. Create a folder called functions in the root of your project

8. 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 and context for you; you’ll want to call the callback 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 a POST 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()
  }
}

9. 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))

10. 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.

Now, for a quick round of questions:

There you have it: a simple guide on Netlify’s serverless functions. Rejoice.

Frontend Developers: I'm redesigning DevTools. Want early access?