#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 57 of 62hard

How to build serverless functions with Node.js?

AWS Lambda and serverless architecture.

What You'll Learn

  • Serverless concepts
  • AWS Lambda functions
  • Serverless Framework

AWS Lambda Handler

code.jsJavaScript
// handler.js
exports.hello = async (event) => {
  const name = event.queryStringParameters?.name || 'World';

  return {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: `Hello, ${name}!` })
  };
};

exports.createUser = async (event) => {
  const body = JSON.parse(event.body);

  // Process user creation
  const user = await saveUser(body);

  return {
    statusCode: 201,
    body: JSON.stringify(user)
  };
};

Serverless Framework

$ terminalBash
npm install -g serverless
config.ymlYAML
# serverless.yml
service: my-api

provider:
  name: aws
  runtime: nodejs20.x
  region: us-east-1

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: /hello
          method: get

  createUser:
    handler: handler.createUser
    events:
      - http:
          path: /users
          method: post
$ terminalBash
# Deploy
serverless deploy

# Test locally
serverless invoke local -f hello

Best Practices

code.jsJavaScript
// Keep functions small and focused
// Initialize outside handler (reused between invocations)
const db = require('./db');

exports.handler = async (event) => {
  // Use existing connection
  return await db.query('SELECT * FROM users');
};