MCPcopy
hub / github.com/dherault/serverless-offline

github.com/dherault/serverless-offline @v14.7.4 sqlite

repository ↗ · DeepWiki ↗ · release v14.7.4 ↗
751 symbols 1,936 edges 375 files 8 documented · 1%
README

Serverless Offline

We are looking for maintainers!

Please contact dherault if you feel you are a good match.

Serverless-offline is supported by the community.

Special thanks to:

  <img src="https://arccode.dev/images/logotype.png" height="64" alt="Arccode">



<b>
  The first role-playing game for developers
</b>



  XP, level ups and guilds. All while you work.

 

This Serverless plugin emulates AWS λ and API Gateway on your local machine to speed up your development cycles. To do so, it starts an HTTP server that handles the request's lifecycle like APIG does and invokes your handlers.

Features

  • Node.js, Python, Ruby, Go, Java (incl. Kotlin, Groovy, Scala) λ runtimes.
  • Velocity templates support.
  • Lazy loading of your handler files.
  • And more: integrations, authorizers, proxies, timeouts, responseParameters, HTTPS, CORS, etc.

This plugin is updated by its users, I just do maintenance and ensure that PRs are relevant to the community. In other words, if you find a bug or want a new feature, please help us by becoming one of the contributors :v: ! See the contributing section.

Documentation

Installation

First, add Serverless Offline to your project:

npm install serverless-offline --save-dev

Then inside your project's serverless.yml file add the following entry to the plugins section: serverless-offline. If there is no plugin section you will need to add it to the file.

Note that the "plugin" section for serverless-offline must be at root level on serverless.yml.

It should look something like this:

plugins:
  - serverless-offline

You can check whether you have successfully installed the plugin by running the serverless command line:

serverless --verbose

The console should display Offline as one of the plugins now available in your Serverless project.

Usage and command line options

In your project root, run:

serverless offline or sls offline.

To list all the options for the plugin, run:

sls offline --help

All CLI options are optional:

corsAllowHeaders

Used as default Access-Control-Allow-Headers header value for responses. Delimit multiple values with commas.

Default: 'accept,content-type,x-api-key'

corsAllowOrigin

Used as default Access-Control-Allow-Origin header value for responses. Delimit multiple values with commas.

Default: '*'

corsDisallowCredentials

When provided, sets the Access-Control-Allow-Credentials header to 'false'.\ Default (without flag): credentials are allowed ('true')

corsExposedHeaders

Used as additional Access-Control-Exposed-Headers header value for responses. Delimit multiple values with commas.

Default: 'WWW-Authenticate,Server-Authorization'

disableCookieValidation

Used to disable cookie-validation on hapi.js-server.

dockerHost

The host name of Docker.

Default: localhost

dockerHostServicePath

Defines the service path used by SLS running inside a Docker container.

dockerNetwork

The network that the Docker container will connect to.

dockerReadOnly

Marks if the docker code layer should be read only.

Default: true

enforceSecureCookies

Enforce secure cookies

host

Host name to listen on.

Default: localhost

httpPort

Http port to listen on.

Default: 3000

httpsProtocol

To enable HTTPS, specify directory (relative to your cwd, typically your project dir) for both cert.pem and key.pem files.

ignoreJWTSignature

When using HttpApi with a JWT authorizer, don't check the signature of the JWT token.

lambdaPort

Lambda http port to listen on.

Default: 3002

layersDir

The directory layers should be stored in.

Default: '${codeDir}/.serverless-offline/layers'

localEnvironment

Copy local environment variables.

Default: false

noAuth

Turns off all authorizers.

noPrependStageInUrl

Don't prepend http routes with the stage.

noSponsor

Remove sponsor message from the output.

noTimeout

Disables the timeout feature.

prefix

Adds a prefix to every path, to send your requests to http://localhost:3000/[prefix]/[your_path] instead.

Default: ''

reloadHandler

Reloads handler with each request.

rubyWatchDirs

List of directories to watch for Ruby file changes. Automatically restarts the Ruby process on change, enabling hot-reload during local development.

resourceRoutes

Turns on loading of your HTTP proxy settings from serverless.yml.

terminateIdleLambdaTime

Number of seconds until an idle function is eligible for termination.

useDocker

Run handlers in a docker container.

useInProcess

Run handlers in the same process as 'serverless-offline'.

webSocketHardTimeout

Set WebSocket hard timeout in seconds to reproduce AWS limits (https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#apigateway-execution-service-websocket-limits-table).

Default: 7200 (2 hours)

webSocketIdleTimeout

Set WebSocket idle timeout in seconds to reproduce AWS limits (https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#apigateway-execution-service-websocket-limits-table).

Default: 600 (10 minutes)

websocketPort

WebSocket port to listen on.

Default: 3001

preLoadModules

Pre-load specified modules in the main thread to avoid crashes when importing in worker threads. Provide module names as a comma-separated list (e.g., "sharp,canvas").

Default: ''

Any of the CLI options can be added to your serverless.yml. For example:

custom:
  serverless-offline:
    httpsProtocol: "dev-certs"
    httpPort: 4000
    foo: "bar"

Options passed on the command line override YAML options.

By default you can send your requests to http://localhost:3000/. Please note that:

  • You'll need to restart the plugin if you modify your serverless.yml or any of the default velocity template files.
  • When no Content-Type header is set on a request, API Gateway defaults to application/json, and so does the plugin. But if you send an application/x-www-form-urlencoded or a multipart/form-data body with an application/json (or no) Content-Type, API Gateway won't parse your data (you'll get the ugly raw data as input), whereas the plugin will answer 400 (malformed JSON). Please consider explicitly setting your requests' Content-Type and using separate templates.

Run modes

node.js

Lambda handlers with serverless-offline for the node.js runtime can run in different execution modes, each with its own pros and cons. They are currently mutually exclusive and it's not possible to use a combination, e.g. use in-process for one Lambda, and worker-threads for another. It is planned to combine the flags into one single flag in the future and also add support for combining run modes.

worker-threads (default)

  • handlers run in their own context
  • memory is not being shared between handlers, memory consumption is therefore higher
  • memory is being released when handlers reload or after usage
  • environment (process.env) is not being shared across handlers
  • global state is not being shared across handlers
  • easy debugging

NOTE:

  • native modules need to be a Node-API addon or be declared as context-aware using NODE_MODULE_INIT(): https://nodejs.org/docs/latest/api/addons.html#worker-support

in-process

  • handlers run in the same context (instance) as serverless and serverless-offline
  • memory is being shared across lambda handlers as well as with serverless and serverless-offline
  • no reloading capabilities as it is [currently] not possible to implement for commonjs handlers (without memory leaks) and for esm handlers
  • environment (process.env) is being shared across handlers as well as with serverless and serverless-offline
  • global state is being shared across lambda handlers as well as with serverless and serverless-offline
  • easy debugging

docker

  • handlers run in a docker container
  • memory is not being shared between handlers, memory consumption is therefore higher
  • memory is being released when handlers reload or after usage
  • environment (process.env) is not being shared across handlers
  • global state is not being shared across handlers
  • debugging more complicated

Python, Ruby, Go, Java (incl. Kotlin, Groovy, Scala)

The Lambda handler process is running in a child process.

Invoke Lambda

To use Lambda.invoke you need to set the lambda endpoint to the serverless-offline endpoint:

import { env } from "node:process"
import aws from "aws-sdk"

const lambda = new aws.Lambda({
  apiVersion: "2015-03-31",
  // endpoint needs to be set only if it deviates from the default
  endpoint: env.IS_OFFLINE
    ? "http://localhost:3002"
    : "https://lambda.us-east-1.amazonaws.com",
})

All your lambdas can then be invoked in a handler using

import { Buffer } from "node:buffer"
import aws from "aws-sdk"

const { stringify } = JSON

const lambda = new aws.Lambda({
  apiVersion: "2015-03-31",
  endpoint: "http://localhost:3002",
})

export async function handler() {
  const clientContextData = stringify({
    foo: "foo",
  })

  const payload = stringify({
    data: "foo",
  })

  const params = {
    ClientContext: Buffer.from(clientContextData).toString("base64"),
    // FunctionName is composed of: service name - stage - function name, e.g.
    FunctionName: "myServiceName-dev-invokedHandler",
    InvocationType: "RequestResponse",
    Payload: payload,
  }

  const response = await lambda.invoke(params).promise()

  return {
    body: stringify(response),
    statusCode: 200,
  }
}

You can also invoke using the AWS CLI by specifying --endpoint-url

aws lambda invoke /dev/null \
  --endpoint-url http://localhost:3002 \
  --function-name myServiceName-dev-invokedHandler

List of available function names and their corresponding serverless.yml function keys are listed after the server starts. This is important if you use a custom naming scheme for your functions as serverless-offline will use your custom name. The left side is the function's key in your serverless.yml (invokedHandler in the example below) and the right side is the function name that is used to call the function externally such as aws-sdk (myServiceName-dev-invokedHandler in the example below):

serverless offline
...
offline: Starting Offline: local/us-east-1.
offline: Offline [http for lambda] listening on http://localhost:3002
offline: Function names exposed for local invocation by aws-sdk:
           * invokedHandler: myServiceName-dev-invokedHandler

To list the available manual invocation paths exposed for targeting by aws-sdk and aws-cli, use SLS_DEBUG=* with serverless offline. After the invoke server starts up, the full list of endpoints will be displayed:

``` SLS_DEBUG=* serverless offline ... offline: Starting Offline: local/us-east-1. ... offline: Offline [http for lambda] listening on http://localhost:3002 offline: Function names exposed for local invocation by aws-sdk: * invokedHandler: myServiceName-dev

Core symbols most depended-on inside this repo

setup
called by 85
tests/_testHelpers/setupTeardown.js
teardown
called by 85
tests/_testHelpers/setupTeardown.js
toObject
called by 58
tests/old-unit/support/OfflineBuilder.js
get
called by 50
src/lambda/Lambda.js
skip
called by 41
tests/manual/websocket/main/test/support/WebSocketTester.js
end
called by 33
tests/old-unit/support/OfflineBuilder.js
create
called by 31
src/events/alb/Alb.js
addFunctionConfig
called by 31
tests/old-unit/support/OfflineBuilder.js

Shape

Function 318
Method 304
Class 129

Languages

TypeScript95%
Python3%
Go2%

Modules by API surface

src/events/http/HttpServer.js26 symbols
tests/integration/alb-handler/src/handler.js24 symbols
tests/integration/handler/src/handler.js22 symbols
src/lambda/LambdaFunction.js20 symbols
src/events/websocket/WebSocketClients.js20 symbols
src/ServerlessOffline.js18 symbols
src/lambda/handler-runner/ruby-runner/RubyRunner.js16 symbols
src/lambda/handler-runner/in-process-runner/aws-lambda-ric/Errors.js15 symbols
src/events/alb/HttpServer.js13 symbols
src/lambda/handler-runner/in-process-runner/aws-lambda-ric/UserFunction.js12 symbols
src/lambda/handler-runner/docker-runner/DockerContainer.js12 symbols
src/lambda/Lambda.js12 symbols

Used by 2 indexed graphs manifest dependencies, hub-wide

Dependencies from manifests, versioned

github.com/aws/aws-lambda-gov1.13.2 · 1×
@apollo/gateway2.8.2 · 1×
@apollo/server4.10.4 · 1×
@apollo/subgraph2.8.2 · 1×
@as-integrations/aws-lambda3.1.0 · 1×
@aws-sdk/client-apigatewaymanagementapi3.504.0 · 1×
@aws-sdk/client-lambda3.1069.0 · 1×
@babel/core7.23.9 · 1×
@babel/plugin-transform-modules-commonjs7.23.3 · 1×
@babel/register7.23.7 · 1×
@hapi/boom10.0.1 · 1×
@hapi/h2o210.0.4 · 1×

For agents

$ claude mcp add serverless-offline \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact