Serverless functions for dummies⚡
Tags: javascript, serverless, aws, node
Published: 2022-11-07 15:45:26

## 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
```

* Add the dependency to run netlify-functions
```
yarn add netlify-lambda
```

* Add the following code under the scripts section of package.json
```
"scripts": {
    "server": "netlify-lambda serve functions",
    "build": "netlify-lambda build functions"
  }
```

- Create a file named `netlify.toml` and add the following in it
```
[build]
  functions = "lambda"
```

* 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}`
  };
}
```

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
```

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


![postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fk3sad6i1rtgpy554zum.png)



##  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
    }
  }
}
```

you can also deploy the function to netlify [Here's a link to the docs](https://docs.netlify.com/functions/deploy/).

Hope this blog was helpful thanks for your time.