@codegenie/serverless-express

repository·mainline·Indexed 26 days ago

https://github.com/codegenieapp/serverless-express

A library that enables Node.js web applications built with frameworks like Express, Koa, and Hapi to run on AWS Lambda, Amazon API Gateway, and Azure Functions. It provides a handler wrapper to transform serverless events into framework-compatible requests and responses, with support for binary settings, custom event source mappings, and asynchronous bootstrap tasks.

Tokens
4.6K
Snippets
18
Records
31
Agent score
90%

What's inside @codegenie/serverless-express

  1. Migrate from aws-serverless-express to @codegenie/serverless-express

    mainline
    The aws-serverless-express NPM package is being deprecated in favor of @codegenie/serverless-express. To stay up to date with maintenance and new features (including Node.js 24 support), you should switch to the new package name.
  2. Upgrade from 4.x to 5.x

    mainline

    When upgrading to v5.x, note the following breaking changes:

    Minimum Node.js Version

    v5.x officially supports Node.js 24 and later.

    Handler Changes

    The handler no longer accepts a callback parameter. You must use async/Promise patterns.

    Removed Options

    The following options are removed and must be replaced:

    • resolutionMode: Removed. Only Promise-based resolution is supported.
    • binaryMimeTypes: Removed. Use binarySettings instead.

    Removed Methods

    • serverlessExpress.createServer(): Use serverlessExpress({ app }) instead.
    • serverlessExpress.proxy(): Use serverlessExpress({ app }) instead.
    • handler.handler(): Use handler() directly.
    • handler.proxy(): Use handler() directly.

    Proxy Path Fix

    v5.x includes a fix for nested routes and custom domains. If you use API Gateway with a custom domain and base path mapping, routes should now work correctly.

    // 5.x (MUST be async/Promise-based)
    export default serverlessExpress({ app })
    
    // 5.x configuration replacement for binaryMimeTypes
    serverlessExpress({
      app,
      binarySettings: {
        contentTypes: ['image/*']
      }
    })
  3. Configure binarySettings in v5.x

    mainline

    In v5.x, binaryMimeTypes has been replaced by binarySettings. This allows you to control how binary data is handled via contentTypes, contentEncodings, and a custom isBinary predicate.

    Use binarySettings to specify which content types should be treated as binary.

    serverlessExpress({
      app,
      binarySettings: {
        isBinary: ({ headers }) => true,
        contentTypes: [],
        contentEncodings: []
      }
    })
  4. Use an async Azure Function v3/v4 handler wrapper

    mainline

    To use Serverless Express with Azure Functions, implement an index.js and a function.json. Note that the out-binding parameter must be named "$return" for the package to work correctly.

    // index.js
    const serverlessExpress = require('@codegenie/serverless-express')
    const app = require('./app')
    const cachedServerlessExpress = serverlessExpress({ app })
    
    module.exports = async function (context, req) {
      return cachedServerlessExpress(context, req)
    }
    // function.json
    {
      "bindings": [
        {
          "authLevel": "anonymous",
          "type": "httpTrigger",
          "direction": "in",
          "name": "req",
          "route": "{*segments}"
        },
        {
          "type": "http",
          "direction": "out",
          "name": "$return"
        }
      ]
    }
  5. Loadtest an Express API in a Serverless environment

    mainline

    You can use the loadtest utility to perform load testing on your deployed serverless endpoint. This helps verify how your API handles specific requests per second (RPS), connections, and concurrency.

    npx loadtest --rps 100 -k -n 1500 -c 50 https://xxxx.execute-api.us-east-1.amazonaws.com/prod/users
  6. Use an async setup Lambda handler for AWS

    mainline

    If your application requires asynchronous bootstrap tasks (like connecting to a database) before handling requests, use the following pattern to ensure the setup runs only once and the instance is cached.

    // lambda.js
    require('source-map-support/register')
    const serverlessExpress = require('@codegenie/serverless-express')
    const app = require('./app')
    
    let serverlessExpressInstance
    
    function asyncTask () {
      return new Promise((resolve) => {
        setTimeout(() => resolve('connected to database'), 1000)
      })
    }
    
    async function setup (event, context) {
      const asyncValue = await asyncTask()
      console.log(asyncValue)
      serverlessExpressInstance = serverlessExpress({ app })
      return serverlessExpressInstance(event, context)
    }
    
    function handler (event, context) {
      if (serverlessExpressInstance) return serverlessExpressInstance(event, context)
    
      return setup(event, context)
    }
    
    exports.handler = handler
  7. Use a minimal AWS Lambda handler wrapper

    mainline

    To wrap an existing Express application for AWS Lambda, create a handler file that exports the result of serverlessExpress({ app }).

    // lambda.js
    const serverlessExpress = require('@codegenie/serverless-express')
    const app = require('./app')
    exports.handler = serverlessExpress({ app })
  8. Configure binarySettings

    mainline

    Use binarySettings to determine if a response should be base64 encoded. This is necessary for binary files like images or compressed files when using event sources like API Gateway that cannot handle binary responses directly. By default, encoding is determined by content-encoding and content-type headers.

    {
      binarySettings: {
        isBinary: ({ headers }) => true,
        contentTypes: ['image/*'],
        contentEncodings: []
      }
    }
  9. Configure eventSourceRoutes for multiple AWS events

    mainline

    Map specific AWS event types to internal routes. This allows a single Lambda function to handle multiple event types (like SNS, SQS, or DynamoDB Streams) by having them POST to the configured routes.

    serverlessExpress({
      app,
      eventSourceRoutes: {
        'AWS_SNS': '/sns',
        'AWS_DYNAMODB': '/dynamodb',
        'AWS_SQS': '/sqs',
        'AWS_EVENTBRIDGE': '/eventbridge',
        'AWS_KINESIS_DATA_STREAM': '/kinesis',
        'AWS_S3': '/s3',
        'AWS_STEP_FUNCTIONS': '/step-functions',
        'AWS_SELF_MANAGED_KAFKA': '/self-managed-kafka',
      }
    })
  10. Access Lambda event and context in v4.x+

    mainline

    In v4.x and later, use getCurrentInvoke from @codegenie/serverless-express to access the Lambda event and context within your application routes, replacing the old middleware approach.

    const { getCurrentInvoke } = require('@codegenie/serverless-express')
    
    router.get('/', (req, res) => {
      const currentInvoke = getCurrentInvoke()
      res.json({
        stage: currentInvoke.event.requestContext.stage
      })
    })