• Tejaya's Blog
  • Posts
  • Serverless Architecture with Node.js: Practical Use Cases

Serverless Architecture with Node.js: Practical Use Cases

Serverless architecture has gained immense popularity as it allows developers to focus on code without worrying about infrastructure. With Node.js, building scalable serverless applications becomes straightforward thanks to its asynchronous nature and ecosystem.

What is Serverless Architecture?

Serverless doesn’t mean “no servers” but refers to cloud providers managing server provisioning, scaling, and maintenance. Popular serverless platforms include AWS Lambda, Azure Functions, and Google Cloud Functions.

Use Cases of Serverless with Node.js

  1. Building REST APIs
    Serverless makes it easy to deploy APIs that scale automatically.

    Example: AWS Lambda with API Gateway

// Lambda function: hello-world.js
exports.handler = async (event) => {
    const name = event.queryStringParameters?.name || "World";
    return {
        statusCode: 200,
        body: JSON.stringify({ message: `Hello, ${name}!` }),
    };
};

Deploy this function on AWS Lambda and expose it using API Gateway for a scalable REST API.

  1. Scheduled Cron Jobs
    Automate repetitive tasks such as database cleanup or sending email reminders.

    Example: Scheduled Job on AWS Lambda

const AWS = require("aws-sdk");
const s3 = new AWS.S3();

exports.handler = async () => {
    const date = new Date().toISOString();
    await s3.putObject({
        Bucket: "my-serverless-logs",
        Key: `log-${date}.txt`,
        Body: `Cron job executed at ${date}`,
    }).promise();

    return { statusCode: 200, body: "Job executed successfully" };
};

Configure a CloudWatch Event to trigger this Lambda function at desired intervals.

  1. Real-Time File Processing
    Automatically process files uploaded to cloud storage.

    Example: Resizing Images with Node.js

const AWS = require("aws-sdk");
const sharp = require("sharp");
const s3 = new AWS.S3();

exports.handler = async (event) => {
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key);
    
    // Fetch the image from S3
    const image = await s3.getObject({ Bucket: bucket, Key: key }).promise();
    
    // Resize the image
    const resizedImage = await sharp(image.Body).resize(300, 300).toBuffer();
    
    // Upload the resized image back to S3
    const newKey = `resized/${key}`;
    await s3.putObject({
        Bucket: bucket,
        Key: newKey,
        Body: resizedImage,
        ContentType: "image/jpeg",
    }).promise();

    return { statusCode: 200, body: `Image resized and saved to ${newKey}` };
};

Trigger this function on S3 events like object uploads.

  1. Webhooks for Real-Time Data
    Handle webhook events, e.g., Stripe payments or GitHub push events.

    Example: GitHub Webhook Handler

exports.handler = async (event) => {
    const body = JSON.parse(event.body);
    const { repository, sender } = body;

    console.log(`Received a push to ${repository.name} by ${sender.login}`);
    return { statusCode: 200, body: "Webhook processed successfully" };
};

Deploy this on AWS Lambda and set up a GitHub webhook pointing to your API Gateway URL.

Why Use Serverless with Node.js?

  • Cost-Effective: Pay only for the compute time used.

  • Auto-Scaling: Handles spikes in traffic without manual intervention.

  • Reduced Maintenance: Focus solely on the application logic.

  • Integration-Friendly: Works seamlessly with services like DynamoDB, S3, and more.

Serverless architecture with Node.js simplifies building scalable, cost-effective applications. Whether you’re deploying APIs, processing files, or handling events, serverless lets you focus on delivering value while the cloud handles the heavy lifting.

Ready to go serverless? Start experimenting with AWS Lambda or other platforms to bring your ideas to life!

Reply

or to participate.