How to use Vercel Cloud Functions

Context

First Read My Article on Cloud Functions to understand why you should learn about them!

Getting Started

  • Create a new folder and initiate a git repo inside of it
  • in this folder create one new subfolder, api
  • Create an index.html in the main folder (just something for us to deploy)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>My Vercel Function Site!</h1>
</body>
</html>
  • in the api folder create a first.js with the following
// Vercel Functions docs => https://vercel.com/docs/serverless-functions/introductionmodule.exports = (req, res) => {
res.json({
body: req.body,
query: req.query,
cookies: req.cookies,
hello: "world",
})
}
  • now commit everything, push up to github and deploy to vercel
  • then to use this function the url would be…
https://myvercelurl/api/first

just to see it grab the url query try out

https://myvercelurl/api/first?cheese=gouda

Try using postman or CURL to make other types of requests like POST, PUT, DELETE

Other Things to Know

  • The req and res objects should work as they do in express.js
  • To enable cors just set the headers like so:
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
}
  • If you are getting a cors error despite having the proper cors errors, it may be because the function is erroring

--

--

--

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Twitter Bot using Python — Enpacto

Create your Twitter Bot using Python

“Git” it together: Some tips on commit etiquette and best practices for junior developers

How I Passed the AWS Solutions Architect Associates (SAA-C02) in One Month

React Custom Hooks #3: useToggle and useBoolean

useToggle and useBoolean usages

Technical Writing Trends in 2020

1M Tcp Connections in C

We’ve got tons of updates, so you’ll want to read this!

Loading, Displaying & Saving images — OpenCV

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Merced Coder

Alex Merced Coder

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

More from Medium

How to simply push from gitlab runner

Odoo Return Order Management from Backend and Frontend

SDK vs API — Why do those two tools usually go hand in hand

From JSON to POJO