DEV Community

Cover image for Serverless functions with Vercel
Diego Guevara
Diego Guevara

Posted on • Updated on

Serverless functions with Vercel

With Vercel, you can deploy Serverless Functions, which are pieces of code written with backend languages like NodeJS, that take an HTTP request and provide a response.

You can use Serverless Functions to handle user authentication, form submission, database queries, custom slack commands, and more.

In this article, we'll create a simple Serverless function with NodeJS, and then deploy it in Vercel.

Create project with an API endpoint

Initialize npm project

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

Now we need to create a folder called /api where our API endpoint files will be.

In this example, we are going to create a file called hello.js, with the following content:

module.exports = (req, res) => {
    res.json({
        hola: 'mundo'    
    })
}
Enter fullscreen mode Exit fullscreen mode

Your project now looks like this

VSCode

In this example our endpoint service will respond with a JSON with the following structure:

{
    hola: 'mundo'
}
Enter fullscreen mode Exit fullscreen mode

Deploy to Vercel

Previously you need to install and configure Vercel CLI.

$ npm i -g vercel
Enter fullscreen mode Exit fullscreen mode

In terminal, at the root of the project write:

$ vercel
Enter fullscreen mode Exit fullscreen mode

Vercel CLI

Now in the Vercel web dashboard you'll see your project and the project URL

Vercel Dashboard

Now, let's test our service in browser, go to the project URL, and remember to add the API Path, in this case is /api/hello

Test in browser

That's all... Now it's your turn, create all the endpoints you need in your API, just remember that each endpoint is a file.

thanks for reading me... and Happy coding ...

Top comments (0)