DEV Community

Elham Najeebullah
Elham Najeebullah

Posted on

Serverless and AWS Lambda with TypeScript example for beginners

A serverless function is a type of cloud computing service that allows you to run code without having to manage any infrastructure. Instead of deploying your code to a server or a cluster of servers, you can simply write and deploy your code as a function, and the cloud provider will automatically execute your code and scale it as needed.

AWS Lambda is a serverless compute service offered by Amazon Web Services (AWS). It allows you to run code in response to a variety of events, such as an HTTP request, a change to a database, or a message being published to a messaging queue.

To use AWS Lambda, you simply write and deploy your code as a function, and then specify the triggers that will invoke your function. For example, you might create a Lambda function that sends an email whenever a new user signs up for your application. When a new user signs up, the cloud provider will automatically execute your Lambda function and send the email.

Here is an example of how you could create an AWS Lambda function with TypeScript that sends a welcoming message to a new user when they sign up with your application:

First, you will need to install the AWS SDK for JavaScript and the @types/aws-lambda type definitions:

npm install aws-sdk @types/aws-lambda
Enter fullscreen mode Exit fullscreen mode

Next, you can create a new file for your Lambda function, sendWelcomeMessage.ts, and import the necessary dependencies:

import { Context, Callback } from 'aws-lambda';
import { SES } from 'aws-sdk';

// Replace with your AWS region
const REGION = 'us-east-1';

// Replace with your sending email address
const SENDER = 'sender@example.com';

// Replace with the recipient email address
const RECIPIENT = 'recipient@example.com';

// The subject and body of the welcome email
const SUBJECT = 'Welcome to our application';
const BODY = `
  <h1>Welcome to our application!</h1>
  <p>Thank you for signing up. We hope you have a great experience using our service.</p>
`;

Enter fullscreen mode Exit fullscreen mode

Then, you can define your Lambda function and use the AWS SDK to send the welcome email:

export function handler(event: any, context: Context, callback: Callback) {
  const ses = new SES({ region: REGION });

  const params = {
    Destination: {
      ToAddresses: [RECIPIENT],
    },
    Message: {
      Body: {
        Html: {
          Charset: 'UTF-8',
          Data: BODY,
        },
      },
      Subject: {
        Charset: 'UTF-8',
        Data: SUBJECT,
      },
    },
    Source: SENDER,
  };

  ses.sendEmail(params, (err, data) => {
    if (err) {
      callback(err);
    } else {
      console.log(`Email sent to ${RECIPIENT} with message Id: ${data.MessageId}`);
      callback(null, data);
    }
  });
}

Enter fullscreen mode Exit fullscreen mode

Finally, you can configure your Lambda function to be triggered by an event, such as a new user sign-up event, and deploy your code to AWS.

What is event argument and context argument inside AWS lambda function?

In an AWS Lambda function, the event argument represents the payload of the event that triggered the function. This can be a wide variety of things, depending on the trigger that you have configured for your function.

For example, if your function is triggered by an HTTP request, the event argument might contain information such as the HTTP method, the path, the headers, and the body of the request. If your function is triggered by a change to a database, the event argument might contain information about the type of change and the data that was changed.

The context argument represents the context in which the function is being executed. It contains information such as the function name, the function version, the AWS request ID, and the identity of the caller.

Here is an example of how you might use the event and context arguments in an AWS Lambda function:

import { SNS } from 'aws-sdk';

export function handler(event: any, context: Context) {
  console.log(`Function name: ${context.functionName}`);
  console.log(`AWS request ID: ${context.awsRequestId}`);

  if (event.Records) {
    event.Records.forEach((record: any) => {
      const sns = record.Sns;
      console.log(`SNS message: ${sns.Message}`);
    });
  }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the function logs the name of the function and the AWS request ID from the context argument, and logs the message of each SNS record from the event argument.

Is AWS cost-effective?
AWS Lambda automatically scales your functions, so you don't have to worry about capacity planning or infrastructure management. You only pay for the compute time that you consume, and you can set concurrency limits to ensure that your functions are executed in a way that meets your performance and cost requirements.

Overall, serverless functions like AWS Lambda can be a convenient and cost-effective way to execute code in the cloud, as you only pay for what you use and don't have to manage any infrastructure.

I hope this helps! Let me know if you have any questions or need further assistance.

Top comments (0)