DEV Community

Cover image for Serverless functions for dummies⚡
ckmonish2000
ckmonish2000

Posted on • Updated on

Serverless functions for dummies⚡

Intro

If you're thinking that you'll be building applications without a server your wrong,

serverless means rather than you managing your servers it would be handled by cloud providers

now you must be thinking then what's the difference between services like Heroku (you don't know what it's because they canceled their free tire a while back),

well with services like Heroku you can choose how you want to structure your app and also note that your app will keep running even if no one is using it.

But with serverless you have to split your logic into individual functions and the code only starts running when you make a request.

There are various options for serverless functions, but the most popular ones are:

  1. AWS Lambda
  2. Cloudflare Workers
  3. Firebase Cloud Functions

In this blog post we will be using AWS Lambda,

With netlify functions under the hood it uses AWS lambda, but it removes the complexity of setting up your environment.

FYI, I would suggest using netlify only for small projects.

Setup

  • initialize package.json
yarn init -y
Enter fullscreen mode Exit fullscreen mode
  • Add the dependency to run netlify-functions
yarn add netlify-lambda
Enter fullscreen mode Exit fullscreen mode
  • Add the following code under the scripts section of package.json
"scripts": {
    "server": "netlify-lambda serve functions",
    "build": "netlify-lambda build functions"
  }
Enter fullscreen mode Exit fullscreen mode
  • Create a file named netlify.toml and add the following in it
[build]
  functions = "lambda"
Enter fullscreen mode Exit fullscreen mode
  • Now create a folder in the root directory called functions.

  • Create a JS file with a name of your choice (Note: Name of the file will be the API endpoint)

Your first function

Let's create a simple function that greets you when you request for it.

exports.handler = async (event, context) => {
  const { name } = JSON.parse(event.body)

  return {
    statusCode: 200,
    body: `hello ${name}`
  };
}
Enter fullscreen mode Exit fullscreen mode

Let me explain the code above:

  • We are exporting an async function that takes in 2 arguments events and context.

FYI: [event gives you access to the headers, body and other properties of the request and the context parameter provides methods and properties that gives you info about the function invocation.]

  • Then you return a object with status code and body of your choice.

Run your serverless app locally

Run the following command in your terminal and it should start your application of port 9000

yarn server
Enter fullscreen mode Exit fullscreen mode

and now you can use postman or your app to query the API you just built.

postman

Fetch live data from an API

Here's another example, which fetches users list from github and returns data only on a GET request.

const axios = require('axios').default;

exports.handler = async (event, context) => {
  let data = await axios.get("https://api.github.com/users")

  if (event.httpMethod === "GET") {
    if (data) {
      return {
        statusCode: 200,
        body: JSON.stringify(data.data)
      }
    } 
  } else {
    return {
      statusCode: 404
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

you can also deploy the function to netlify Here's a link to the docs.

Hope this blog was helpful thanks for your time.

Top comments (2)

Collapse
 
strongunsullied profile image
Kasope Johnson

Thank you! Finally have an idea of what serveless functions are!

Collapse
 
ckmonish2000 profile image
ckmonish2000

Glad I could help 😊