Setting up a Serverless service and exposing it over HTTP
AWS Lambda is straightforward enough to configure on its own, but the surrounding AWS landscape makes it hard to see how functions fit into an ordinary web application. The Serverless framework handles the creation and deployment of functions and, most importantly, their integration into a web app. Start with the quick start guide for installation and AWS account setup; with an account already in place, you can be running in 5–10 minutes. (If Lambda itself is new to you, begin with the AWS intro.)
Creating the service
Pick a directory in an existing web app where your services live (create-react-app will spin up a project quickly), cd into it, and run:
sls create -t aws-nodejs --path hello-world
The command produces a hello-world directory:

handler.js contains an async function returning a message, and running sls deploy would already put that function in the cloud. To make it callable over the web, however, edit serverless.yaml. Doing the same job by hand in AWS would mean opening API Gateway, creating an endpoint and a stage, and proxying it to the Lambda. Serverless compresses that into configuration:

The file ships with commented boilerplate for common setups. Uncomment the http entries and give them a sensible path:
functions:
hello:
handler: handler.hello
# The following are a few example events you can configure
# NOTE: Please make sure to change your handler code to work with those events
# Check the event documentation for details
events:
- http:
path: msg
method: get
Enabling CORS on both sides
Calling the endpoint from front-end JavaScript via the Fetch API requires CORS. Adding cors: true below the configuration above handles the API endpoint:
functions:
hello:
handler: handler.hello
events:
- http:
path: msg
method: get
cors: true
The endpoint being configured is only half the job: the Lambda itself must return the appropriate headers. Automate this by adding a function to handler.js:
const CorsResponse = obj => ({
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*"
},
body: JSON.stringify(obj)
});
Then pass the Lambda's return value through it. Here is the complete handler.js at this stage:
'use strict';
const CorsResponse = obj => ({
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*"
},
body: JSON.stringify(obj)
});
module.exports.hello = async event => {
return CorsResponse("HELLO, WORLD!");
};
Deploying and finding the URL
Run sls deploy from inside hello-world. The function is now live behind an HTTP endpoint reachable with Fetch. Locating that endpoint by digging through the AWS console for the gateway API Serverless created and its Invoke URL works, and looks roughly like this:

sls info is easier:

It reports the path where the function is available:
https://6xpmc3g0ch.execute-api.us-east-1.amazonaws.com/dev/ms
Fetch it from a web app like so:
fetch("https://6xpmc3g0ch.execute-api.us-east-1.amazonaws.com/dev/msg")
.then(resp => resp.json())
.then(resp => {
console.log(resp);
});
The message should appear in the dev console.

A second, more useful function: image resizing
The canonical resize-an-image Lambda is usually triggered by an S3 upload. Here the user uploads an image straight to the Lambda instead, which removes any need to bundle aws-sdk resources into the client-side bundle. The function takes an image, resizes it, and uploads the result to an S3 bucket. Create a new service — cover-art in this example:
sls create -t aws-nodejs --path cover-art
Add an HTTP path, this time a POST since the file is being sent rather than received, and enable CORS:
// Same as before
events:
- http:
path: upload
method: post
cors: true
Next, grant the function access to the S3 bucket. Uncomment the boilerplate in the YAML's iamRoleStatements section and adjust it:
iamRoleStatements:
- Effect: "Allow"
Action:
- "s3:*"
Resource: ["arn:aws:s3:::your-bucket-name/*"]
The trailing /* matters: the configuration lists paths to resources, not isolated bucket names, so this covers any resource inside your-bucket-name. Because files are uploaded directly to the Lambda, the API endpoint also has to accept multipart/form-data as a binary media type. Find the provider section:
provider:
name: aws
runtime: nodejs12.x
…and change it to:
provider:
name: aws
runtime: nodejs12.x
apiGateway:
binaryMediaTypes:
- 'multipart/form-data'
Finally, give the function a meaningful name: replace handler: handler.hello with handler: handler.upload, and rename module.exports.hello to module.exports.upload in handler.js.
The function code
Install the helpers:
npm i jimp uuid lambda-multipart-parser
Jimp resizes the uploaded images; uuid generates new, unique file names for the sized resources before they go to S3; and lambda-multipart-parser parses the file information inside the Lambda. A convenience helper wraps the S3 upload:
const uploadToS3 = (fileName, body) => {
const s3 = new S3({});
const params = { Bucket: "your-bucket-name", Key: `/${fileName}`, Body: body };
return new Promise(res => {
s3.upload(params, function(err, data) {
if (err) {
return res(CorsResponse({ error: true, message: err }));
}
res(CorsResponse({
success: true,
url: `https://${params.Bucket}.s3.amazonaws.com/${params.Key}`
}));
});
});
};
The core code reads the uploaded files, resizes them with Jimp where needed, and uploads the results to S3:
'use strict';
const AWS = require("aws-sdk");
const { S3 } = AWS;
const path = require("path");
const Jimp = require("jimp");
const uuid = require("uuid/v4");
const awsMultiPartParser = require("lambda-multipart-parser");
const CorsResponse = obj => ({
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*"
},
body: JSON.stringify(obj)
});
const uploadToS3 = (fileName, body) => {
const s3 = new S3({});
var params = { Bucket: "your-bucket-name", Key: `/${fileName}`, Body: body };
return new Promise(res => {
s3.upload(params, function(err, data) {
if (err) {
return res(CorsResponse({ error: true, message: err }));
}
res(CorsResponse({
success: true,
url: `https://${params.Bucket}.s3.amazonaws.com/${params.Key}`
}));
});
});
};
module.exports.upload = async event => {
const formPayload = await awsMultiPartParser.parse(event);
const MAX_WIDTH = 50;
return new Promise(res => {
Jimp.read(formPayload.files[0].content, function(err, image) {
if (err || !image) {
return res(CorsResponse({ error: true, message: err }));
}
const newName = `${uuid()}${path.extname(formPayload.files[0].filename)}`;
if (image.bitmap.width > MAX_WIDTH) {
image.resize(MAX_WIDTH, Jimp.AUTO);
image.getBuffer(image.getMIME(), (err, body) => {
if (err) {
return res(CorsResponse({ error: true, message: err }));
}
return res(uploadToS3(newName, body));
});
} else {
image.getBuffer(image.getMIME(), (err, body) => {
if (err) {
return res(CorsResponse({ error: true, message: err }));
}
return res(uploadToS3(newName, body));
});
}
});
});
};
The grunt work is deliberately left terse — a different image library would produce quite different code. On the client, the example uses react-dropzone:
<Dropzone
onDrop={files => onDrop(files)}
multiple={false}
>
<div>Click or drag to upload a new cover</div>
</Dropzone>
…with an onDrop handler:
const onDrop = files => {
let request = new FormData();
request.append("fileUploaded", files[0]);
fetch("https://yb1ihnzpy8.execute-api.us-east-1.amazonaws.com/dev/upload", {
method: "POST",
mode: "cors",
body: request
})
.then(resp => resp.json())
.then(res => {
if (res.error) {
// handle errors
} else {
// success - woo hoo - update state as needed
}
});
};
Uploading a file this way places it in the S3 bucket.

Optional: shrinking the deployment with webpack
By default Serverless zips the entire services folder and sends all of it to Lambda — 10MB here, since node_modules comes along. A bundler shrinks that considerably and also improves deploy time, data usage and cold start performance. A plugin integrates webpack into the Serverless build:
npm i serverless-webpack --save-dev
Register it at the end of the YAML config:
// Same as before
plugins:
- serverless-webpack
Then supply a webpack.config.js:
const path = require("path");
module.exports = {
entry: "./handler.js",
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, '.webpack'),
filename: 'handler.js',
},
target: "node",
mode: "production",
externals: ["aws-sdk"],
resolve: {
mainFields: ["main"]
}
};
Several details in that file matter. target: node makes Node-specific assets resolve correctly, and you may need the output filename set to handler.js. aws-sdk is listed in externals so webpack leaves const AWS = require("aws-sdk"); for the Lambda to resolve at runtime, which is fine because Lambdas have aws-sdk available implicitly — no need to send it over the wire. mainFields: ["main"] tells webpack to ignore ESM module fields, which fixes some issues with Jimp. Re-deploy and webpack should run:

The code is now a single bundled file of 935K, which zips down to 337K.
Additional data and environment variables
To send other data to the Lambda, add fields to the FormData request object:
request.append("xyz", "Hi there");
Then read formPayload.xyz inside the Lambda — useful for a security token or other file information. Environment variables are configured the same way, as fields in serverless.yaml, and can be read from an external file that presumably stays out of git; this post by Philipp Müns covers the details.
Where to go next
These two services barely touch what Serverless offers. For further study, David Wells (an engineer at Netlify and formerly of the Serverless team) and Swizec Teller provide useful material:
- Serverless Workshop: a repo for learning the core concepts of serverless
- Serverless Auth Strategies: a repo walking through strategies for authorizing access to functions
- Netlify Functions Workshop: Netlify lessons on the core concepts of serverless functions
- Serverless Handbook: getting started with serverless technologies



