Your first cloud function
The core feature of serverless you'll use are cloud functions. They make things happen. We'll take a look at 3 providers and how they make cloud functions working.
Starting with the good old hello world 😊
Vercel
Vercel uses an ExpressJS-like cloud functions and filename routing. Files in /api
turn into cloud functions at the same path as their name.
Exercise
Create a new project with an /api
directory and add a JavaScript file. Export an async method (using module.exports =
) that accepts a req
and res
argument.
Use the .status
and .send
methods on res
to return a string.
Deploy your project with the vercel
command. Use default answers to prompts.
Try your function
Leave payload empty for GET requests, valid JSON for POST.
Solution
Netlify
Netlify's cloud functions behave as a thin wrapper on AWS Lambda. You get a more universal environment and codebase at the cost of more configuration work.
Unlike Vercel, Netlify supports certain event-driven functions.
Exercise
Create a new project with an /functions
directory and add a JavaScript file. Export an async handler method (using exports.handler =
) that accepts an event
argument.
Return an object with a statusCode
and a body
.
{statusCode: 200,body: "Hello world"}
Add a netlify.toml
config file at the root:
[build]functions = "functions"
Deploy with netlify deploy
, set up as a new project.
Try your function
Leave payload empty for GET requests, valid JSON for POST.
Solution
AWS Lambda
AWS Lambda gives you access to the full power of serverless and is also the most cumbersome to use. You can use their UI but I don't recommend it.
Using a code-as-infra approach gets you close to the Netlify and Vercel developer experience. You can use AWS's official CloudFormation tooling, but I find Serverless Framework a more welcoming approach.
Serverless Framework is open source tooling working on top of CloudFormation. Makes common operations easier and lets you drop down to CloudFormation when you need more power.
Exercise
Clone the serverless-workshop-exercises GitHub repository and start with exercise-1
. You get a repository configured for serverless and I've added build and deploy scripts.
It's set up with TypeScript - helps cut down debugging time, you'll see.
Create a src/hello.ts
file that exports a handler
function. Return a response object just like in the Netlify example.
Deploy with yarn deploy
or npm run deploy
.
PS: if you're not well versed in TypeScript yet, don't worry. We won't use anything crazy at this workshop.
Try your function
Leave payload empty for GET requests, valid JSON for POST.
Solution
https://github.com/Swizec/serverless-workshop-exercises/tree/exercise-1-solution