# An introduction to digital ocean functions

Recently I came across a post by the digital ocean where they introduced us to the serverless functions which they recently launched. I'm a huge fan of them in terms of simplicity and pricing. 

I thought of giving it a try and found it to be really easy to set up and deploy. 

In this post, I'll help you in creating your first serverless function on Digital Ocean, how to deploy them and all the necessary steps.

Enjoy the post✌🏻.

## 🎳 Getting started with DO Functions

![digital ocean functions.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1653602768228/paoze-A5s.png align="left")

### 👤 Create a Digital Ocean account
If you don't have a digital ocean account, you can create one [here](https://m.do.co/c/72f15e1dc143).
[![DigitalOcean Referral Badge](https://web-platforms.sfo2.digitaloceanspaces.com/WWW/Badge%202.svg)](https://www.digitalocean.com/?refcode=72f15e1dc143&utm_campaign=Referral_Invite&utm_medium=Referral_Program&utm_source=badge)

> This link will give you free $100💸 for your testing with a validity of 60 days. You can use this credit for all your tests related to droplets or serverless.

Once you have the account, we can now move on to installing the **doctl CLI** which will help us in bootstrapping the serverless app.

### ⬇️ Install doctl
If you are on a **Mac**, you can install **doctl** with [homebrew](https://brew.sh/). 

```bash
brew install doctl
``` 

For **Linux**, you can use [Snap Package](https://snapcraft.io/docs/installing-snapd)

```bash
sudo snap install doctl
``` 

For **Windows**, you can use the below commands on your Powershell. Open Powershell with **Run as Administrator** 

```bash
Invoke-WebRequest https://github.com/digitalocean/doctl/releases/download/v1.76.0/doctl-1.76.0-windows-amd64.zip -OutFile ~\doctl-1.76.0-windows-amd64.zip
``` 
This will download the most recent version of **doctl**. We can now proceed with the unzip of the file.

```bash
Expand-Archive -Path ~\doctl-1.76.0-windows-amd64.zip
``` 
We can now move the **doctl** into a dedicated directory and add it to your system’s path by running:

```bash
New-Item -ItemType Directory $env:ProgramFiles\doctl\
Move-Item -Path ~\doctl-1.76.0-windows-amd64\doctl.exe -Destination $env:ProgramFiles\doctl\
[Environment]::SetEnvironmentVariable(
    "Path",
    [Environment]::GetEnvironmentVariable("Path",
    [EnvironmentVariableTarget]::Machine) + ";$env:ProgramFiles\doctl\",
    [EnvironmentVariableTarget]::Machine)
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine")
``` 
>You can also find a how-to guide 📖 on installing and configuring **doctl** by following this [link](https://docs.digitalocean.com/reference/doctl/how-to/install/).

Once done, we can now proceed with creating of API Token.

### 🔑 Create an API token 
To generate a personal access token, you first need to log in to your digital ocean [control panel](https://cloud.digitalocean.com/). 

Click on the **API** link in the sidebar. When on the **Tokens/Keys** tab of the **Personal access tokens** section, click the **Generate New Token** button.

A New personal access token window will appear.

You can set the name to whatever you want and the same with the expiry of the token. Make sure to give **both read and write access** while generating the token.

>Make sure to copy it safely as it will not be shown again.

You can also follow [this link](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to generate a personal access token on the digital ocean.

We can now proceed with the access token to provide access to **doctl**.

### 🔓 Use API token to grant account access to doctl

Run the following command and when prompted, pass the token string. You can also give this auth context a name.

```bash
doctl auth init --context <NAME>
# ex doctl auth init --context serverless
``` 

You can add multiple accounts and can switch between auth contexts.

```bash
doctl auth list
doctl auth switch --context <NAME>
``` 

We can now proceed with the validation of the doctl.

### ✅ Validate if the doctl is working

You can review your account details by running the following command to confirm you have successfully authorised **doctl**.

```bash
doctl account get
``` 

If authorized successfully, you will get something like this.

```bash
Email                    Droplet Limit    Email Verified    UUID                                    Status
pratik@gmail.com    10               true              d0161b45-8c09-4233-dv32-63614c84a0dd    active
``` 

Now we are ready to proceed with installing the support for serverless.

### ⬇️ Install support for serverless functions

To install the support for serverless Functions, we need to install a software extension for that.

```bash
doctl serverless install
``` 

You'll get installation status something like this.

```bash
Downloading...Unpacking...Installing...Cleaning up...
Done
``` 

Next, we need to connect to the development namespace with the following command.


```bash
doctl serverless connect
``` 

It will show the name and API host of your namespace.


We are now ready to proceed with the creation of our first serverless app.

### 🖥 Create a serverless app

Navigate to the directory where you want your functions to stay and then run the following command.

```bash
doctl serverless init --language js do-serverless
``` 

The **-l** or **--language** flag specifies which programming language to use. We have option for **go**, **javascript**, **php**, and **python**.

A directory named **do-serverless** will be created with sample code for "hello world" and configuration files.


```bash
do-serverless/
├── packages
│   └── sample
│       └── hello
│           └── hello.js
└── project.yml
``` 

We don't have to make any changes to the js file, it can be used as it is, we just need to deploy the code to test.

### ⬆️ Deploy the serverless app

In order to deploy the serverless code, we need to come out of the directory `do-serverless` and run the following command.

```bash
doctl serverless deploy do-serverless
``` 

And if you are in the same directory, you can run `doctl serverless deploy .` 


### 🔗 Requesting the live URL of the function
You can request the live URL of the function with the following command.

```bash
doctl sbx fn get sample/hello --url
``` 

This will give you the URL something like this.

```bash
https://faas-blr1-22237d592.doserverless.co/api/v1/web/fn-29f27939-608f-4a63-8b2f-6a35e24c7613/sample/hello
``` 

You can also list all of your deployed functions with the following command.

```bash
doctl serverless functions list
``` 


```bash
Datetime        Access   Kind      Version  Actions
─────────────── ──────── ───────── ──────── ─────────────────────────────────────────────────
05/25 01:56:34  web      nodejs:14 0.0.1    sample/hello
``` 

### 👀 Developing in watch mode
We can also develop our functions in watch mode as it can speed up our development time as it will keep on watching for code changes and automating build steps.

To develop in watch mode, run the following command:

```bash
doctl serverless watch do-serverless
``` 

When you are done with the development, press `CTRL+C` to exit the watch mode.

### 🕵🏻‍♂️ Inspecting the logs
We can also see the logs from your functions. Just run the following command.

```bash
doctl serverless activations logs --limit 3
``` 

By default, the limit is 1. We can also add the `--follow` flag to follow the logs as they are generated.

We can also follow logs from a specific function with the help of the following command.

```bash
doctl serverless activations logs --follow --function sample/hello
``` 

## ❤️ Final thought
I tried and deployed my function and was able to get a decent response time (~140ms) and this was actually good as compared to [Firebase Functions](https://firebase.google.com/docs/functions) which I used in the last project.

Hopefully, I'll try building a couple of projects using DO Functions and see how it performs. So far I really liked how easy was it to set up😀.

You can follow the [actual doc](https://docs.digitalocean.com/products/) from the digital ocean for complete information on functions and the official post [here](https://www.digitalocean.com/blog/introducing-digitalocean-functions-serverless-computing).

I hope this post will help you in creating your first serverless function on the digital ocean. If you found this post helpful, please share this post with others and also leave a comment below and let me know your thoughts.

Thanks for the time, see you in my next post.

❤



