Build a Serverless Application with Node.js and AWS Lambda
In this blog post, we will walk through the process of creating a serverless application using Node.js and AWS Lambda. Serverless applications have gained popularity in recent years due to their ability to scale automatically and reduce infrastructure management overhead. With AWS Lambda, you can run your code without provisioning or managing servers, and pay only for the compute time you consume. This tutorial is beginner-friendly and assumes no prior experience with AWS Lambda or Node.js. By the end of this tutorial, you will have built a simple serverless application that can be easily deployed on AWS.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js (version 14.x or later)
- npm (included with Node.js)
- AWS CLI (version 2.x)
- Serverless Framework
Getting Started
To begin, we will create a new Node.js project and initialize it with the necessary dependencies:
$ mkdir serverless-app $ cd serverless-app $ npm init -y
Now, we will install the AWS SDK and Serverless Framework as dependencies:
$ npm install --save aws-sdk serverless
Next, we will create a serverless.yml
file in the project's root directory. This file will contain the configuration for our serverless application:
service: serverless-app provider: name: aws runtime: nodejs14.x functions: hello: handler: handler.hello
In the serverless.yml
file, we define a single Lambda function called hello
with a handler located in the handler.js
file. Now, let's create the handler.js
file:
module.exports.hello = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: 'Hello from our serverless application!', }), }; };
This simple Lambda function returns a JSON response with a "Hello from our serverless application!" message.
Deploying the Application
To deploy the application, we will use the Serverless Framework. First, make sure you have configured the AWS CLI with your AWS credentials. If you haven't done so, follow the official AWS CLI documentation for instructions.
Now, we can deploy our application by running the following command:
$ npx serverless deploy
This command will package and deploy your Lambda function to AWS. Once the deployment is complete, you will see output similar to the following:
Serverless: Packaging service... Serverless: Excluding development dependencies... Serverless: Creating Stack... Serverless: Checking Stack create progress... ...... Serverless: Stack create finished... Serverless: Uploading CloudFormation file to S3... Serverless: Uploading artifacts... Serverless: Uploading service serverless-app.zip file to S3 (1.83 MB)... Serverless: Validating template... Serverless: Updating Stack... Serverless: Checking Stack update progress... ........................... Serverless: Stack update finished... Service Information service: serverless-app stage: dev region: us-east-1 stack: serverless-app-dev resources: 6 api keys: None endpoints: None functions: hello: serverless-app-dev-hello layers: None
The Lambda function is now deployed andready to be invoked. However, we haven't defined any triggers or endpoints for our function yet. Let's create an HTTP endpoint for our Lambda function using API Gateway.
Adding an API Gateway Trigger
To add an API Gateway trigger, update the serverless.yml
file as follows:
service: serverless-app provider: name: aws runtime: nodejs14.x functions: hello: handler: handler.hello events: - http: path: hello method: get
We've added an events
section to our hello
function, specifying an HTTP event with a GET
method and a /hello
path. This will create an API Gateway resource and map it to our Lambda function.
Now, we can redeploy our application:
$ npx serverless deploy
Once the deployment is complete, you will see a new endpoints
section in the output:
endpoints: GET - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello
Testing the Application
To test the application, you can either use your web browser, a tool like Postman, or a command-line tool like curl
:
$ curl https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello
Replace xxxxxxxxxx
with the actual identifier in your API Gateway endpoint URL. The response should be the JSON object we defined in our Lambda function:
{"message":"Hello from our serverless application!"}
Additional Functionality
Let's expand our serverless application by adding a new function that accepts a name as a query parameter and returns a personalized greeting.
Update the handler.js
file with a new function:
module.exports.greet = async (event) => { const name = event.queryStringParameters && event.queryStringParameters.name || 'stranger'; return { statusCode: 200, body: JSON.stringify({ message: `Hello, ${name}!`, }), }; };
Now, update the serverless.yml
file to include the new function and endpoint:
service: serverless-app provider: name: aws runtime: nodejs14.x functions: hello: handler: handler.hello events: - http: path: hello method: get greet: handler: handler.greet events: - http: path: greet method: get
Redeploy the application:
$ npx serverless deploy
You should now see two endpoints in the output:
endpoints: GET - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello GET - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/greet
Test the new /greet
endpoint with a query parameter:
$ curl "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/greet?name=Jane"
The response should be a personalized greeting:
{"message":"Hello, Jane!"}
Cleaning Up
To remove the deployed resources and avoid incurring any further costs, run the following command:
$ npx serverless remove
This command will delete the CloudFormation stack and all associated resources.
Conclusion
In this tutorial, we have built a simple serverless application using Node.js and AWS Lambda. We used the Serverless Framework to define, package, anddeploy our application, making it easy to manage our serverless resources. We also added API Gateway triggers to create HTTP endpoints for our Lambda functions, allowing us to interact with our application via RESTful API calls.
Serverless applications offer several benefits, such as reduced infrastructure management, automatic scaling, and cost efficiency. With the knowledge gained in this tutorial, you can start building more complex serverless applications to leverage these advantages.
Here are some additional topics you can explore to further enhance your serverless application:
- Add authentication and authorization using AWS Cognito or a third-party identity provider.
- Store and retrieve data using serverless databases like Amazon DynamoDB or AWS Aurora Serverless.
- Implement a serverless file storage system using Amazon S3.
- Integrate with other AWS services, such as SNS, SQS, and Kinesis, for event-driven processing and messaging.
Remember, the possibilities with serverless applications are vast, and this tutorial is just the beginning. Continue learning and exploring to unlock the full potential of serverless computing.
Sharing is caring
Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: