DEV Community

Kuvam Bhardwaj
Kuvam Bhardwaj

Posted on

Creating Serverless Functions with Vercel

Introduction

Looking for a serverless hosting service is a big pain when you just want to taste or even host a small project on it. Today, I found a new resource which lets you create serverless functions for absolutely free! Vercel. So, lets build & deploy our first Serverless function on it!

Setup

The platform requires us to install its CLI in order to develop & deploy our functions. Lets do npm i -g vercel to install the CLI globally. After creating a new directory, we'll initialize it as a new node project.
new node project init

Development Workflow

Vercel cli expects us to put all of our .js files in a folder called /api.
The .js files will contain 1 default exported function which represents a REST API endpoint taking 2 parameters request & response representing the express's Request & Response objects respectively (just like in normal express.js GET/POST endpoints).
The url at which the endpoints will be hosted will be /api/{name-of-file}

Creating Our First Serverless Function

So I have created a basic node.js project with following files:
basic serverless nodejs app file structure

index.js file

hello.js file

"But how I will develop them without even testing?"

CLI To The Rescue

The vercel cli which we just just installed globally provides a functionality to run the functions on our own local machines.
You will be required by the CLI to login/signup into a vercel account, join me from here after completing that ;)
Now, to run them, we must do vercel dev. For the first time running the cli, it requires us to do some quick configs & settings, after completing that you should see something like this:
vercel cli setup and development environment

To check how the functions are working locally, we have to go to http://localhost:3000/api & to access the endpoint in hello.js, we will go to http://localhost:3000/api/hello

index.js serverless function endpoint

hello.js serverless function endpoint

Everything looks awesome! lets deploy it on vercel!

Deploying Functions on Vercel

Vercel's CLI makes deploying functions as easy as running a command on the terminal, we'll now run vercel on our terminal in the root of the directory.
deplying serverless function with 1 command on vercel

HERE YOU GO!
deployed

You can check limits for a free plan set by the platform here.

Discussion (0)