Install the serverless framework
1
npm install -g serverless
Configure AWS IAM keys
Replace [Access key ID] and [Secret access key] with your IAM credentials. If you don’t have it, create one in the AWS console, My Security Credentials.
1
serverless config credentials --provider aws --key [Access key ID] --secret [Secret access key]
Generate a boilerplate
1
serverless create --template aws-nodejs --path [folder]
Then it will create a boilerplate using the template for Node.js. Go into the root folder, and install the required packages.
1
2cd [folder]
npm init -y && npm installAnd also install
express
andserverless-http
with the command below:1
npm install express serverless-http
- Expose an HTTP endpoint
In the serverless.yml
file, comment out and change the following code:
1 | functions: |
Set up Express
Delete
handler.js
file, and create one namedapp.js
:1
2
3
4
5
6
7
8
9const express = require('express');
const app = express();
const sls = require('serverless-http');
app.get('/', async (req, res, next) => {
res.status(200).send('Hello Serverless!')
});
module.exports.server = sls(app);Noticed that, AWS Lambda does not support the ES6
import
specifier (at the time of 10/10/2019).import express from 'express'
will cause an internal server error. And in the log we can see that it says"Runtime.UserCodeSyntaxError: SyntaxError: Unexpected identifier"
- Deploy
1 | serverless deploy |
Test the API
In the output, we can see that it exposes an endpoint probably like this.
1
2endpoints:
GET - https://xxxx.execute-api.xx-xxxx-x.amazonaws.com/xxx/Let’s try it with the command below:
1
curl https://xxxx.execute-api.xx-xxxx-x.amazonaws.com/xxx/
And we will get our message back, “It’s working”.