Gathering detailed insights and metrics for serverless-offline
Gathering detailed insights and metrics for serverless-offline
Gathering detailed insights and metrics for serverless-offline
Gathering detailed insights and metrics for serverless-offline
Emulate AWS λ and API Gateway locally when developing your Serverless project
npm install serverless-offline
60.8
Supply Chain
87.8
Quality
95.1
Maintenance
100
Vulnerability
96.6
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
5,204 Stars
3,909 Commits
795 Forks
65 Watching
8 Branches
279 Contributors
Updated on 26 Nov 2024
JavaScript (96.64%)
Python (0.88%)
Shell (0.72%)
Ruby (0.52%)
Go (0.43%)
TypeScript (0.21%)
Scala (0.17%)
Groovy (0.16%)
Kotlin (0.14%)
Makefile (0.07%)
Dockerfile (0.06%)
Cumulative downloads
Total Downloads
Last day
-1.6%
104,271
Compared to previous day
Last week
2.3%
531,793
Compared to previous week
Last month
-0%
2,249,217
Compared to previous month
Last year
5.8%
27,136,524
Compared to previous year
25
1
Serverless-offline is supported by the community.
Special thanks to: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
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.
process.env.IS_OFFLINE
variableFirst, add Serverless Offline to your project:
npm install serverless-offline --save-dev
Then inside your project's serverless.yml
file add 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:
1plugins: 2 - 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.
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:
Used as default Access-Control-Allow-Headers header value for responses. Delimit multiple values with commas.
Default: 'accept,content-type,x-api-key'
Used as default Access-Control-Allow-Origin header value for responses. Delimit multiple values with commas.
Default: '*'
When provided, the default Access-Control-Allow-Credentials header value will be passed as 'false'.
Default: true
Used as additional Access-Control-Exposed-Headers header value for responses. Delimit multiple values with commas.
Default: 'WWW-Authenticate,Server-Authorization'
Used to disable cookie-validation on hapi.js-server.
The host name of Docker.
Default: localhost
Defines service path which is used by SLS running inside Docker container.
The network that the Docker container will connect to.
Marks if the docker code layer should be read only.
Default: true
Enforce secure cookies
-o Host name to listen on.
Default: localhost
Http port to listen on.
Default: 3000
-H To enable HTTPS, specify directory (relative to your cwd, typically your project dir) for both cert.pem and key.pem files.
When using HttpApi with a JWT authorizer, don't check the signature of the JWT token.
Lambda http port to listen on.
Default: 3002
The directory layers should be stored in.
Default: ${codeDir}/.serverless-offline/layers'
Copy local environment variables.
Default: false
Turns off all authorizers.
Don't prepend http routes with the stage.
Remove sponsor message from the output.
-t Disables the timeout feature.
-p Adds a prefix to every path, to send your requests to http://localhost:3000/[prefix]/[your_path] instead.
Default: ''
Reloads handler with each request.
Turns on loading of your HTTP proxy settings from serverless.yml.
Number of seconds until an idle function is eligible for termination.
Run handlers in a docker container.
Run handlers in the same process as 'serverless-offline'.
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)
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)
WebSocket port to listen on.
Default: 3001
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:
1custom: 2 serverless-offline: 3 httpsProtocol: 'dev-certs' 4 httpPort: 4000 5 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:
serverless.yml
or any of the default velocity template files.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 as input), whereas the plugin will answer 400 (malformed JSON).
Please consider explicitly setting your requests' Content-Type and using separate templates.Lambda handlers with serverless-offline
for the node.js
runtime can run in different execution modes and have some differences with a variety of 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.
NOTE:
serverless
and serverless-offline
serverless
and serverless-offline
serverless
and serverless-offline
serverless
and serverless-offline
the Lambda handler process is running in a child process.
To use Lambda.invoke
you need to set the lambda endpoint to the serverless-offline
endpoint:
1import { env } from "node:process"
2import aws from "aws-sdk"
3
4const lambda = new aws.Lambda({
5 apiVersion: "2015-03-31",
6 // endpoint needs to be set only if it deviates from the default
7 endpoint: env.IS_OFFLINE
8 ? "http://localhost:3002"
9 : "https://lambda.us-east-1.amazonaws.com",
10})
All your lambdas can then be invoked in a handler using
1import { Buffer } from "node:buffer" 2import aws from "aws-sdk" 3 4const { stringify } = JSON 5 6const lambda = new aws.Lambda({ 7 apiVersion: "2015-03-31", 8 endpoint: "http://localhost:3002", 9}) 10 11export async function handler() { 12 const clientContextData = stringify({ 13 foo: "foo", 14 }) 15 16 const payload = stringify({ 17 data: "foo", 18 }) 19 20 const params = { 21 ClientContext: Buffer.from(clientContextData).toString("base64"), 22 // FunctionName is composed of: service name - stage - function name, e.g. 23 FunctionName: "myServiceName-dev-invokedHandler", 24 InvocationType: "RequestResponse", 25 Payload: payload, 26 } 27 28 const response = await lambda.invoke(params).promise() 29 30 return { 31 body: stringify(response), 32 statusCode: 200, 33 } 34}
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, 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-invokedHandler
[offline] Lambda Invocation Routes (for AWS SDK or AWS CLI):
* POST http://localhost:3002/2015-03-31/functions/myServiceName-dev-invokedHandler/invocations
[offline] Lambda Async Invocation Routes (for AWS SDK or AWS CLI):
* POST http://localhost:3002/2014-11-13/functions/myServiceName-dev-invokedHandler/invoke-async/
You can manually target these endpoints with a REST client to debug your lambda
function if you want to. Your POST
JSON body will be the Payload
passed to your function if you were
to calling it via aws-sdk
.
process.env.IS_OFFLINE
variableWill be "true"
in your handlers when using serverless-offline
.
To use layers with serverless-offline, you need to have the useDocker
option set to true. This can either be by using the --useDocker
command, or in your serverless.yml like this:
1custom: 2 serverless-offline: 3 useDocker: true
This will allow the docker container to look up any information about layers, download and use them. For this to work, you must be using:
If you're using least-privilege principals for your AWS roles, this policy should get you by:
1{ 2 "Statement": [ 3 { 4 "Action": "lambda:GetLayerVersion", 5 "Effect": "Allow", 6 "Resource": "arn:aws:lambda:*:*:layer:*:*" 7 } 8 ], 9 "Version": "2012-10-17" 10}
Once you run a function that boots up the Docker container, it'll look through the layers for that function, download them in order to your layers folder, and save a hash of your layers so it can be re-used in future. You'll only need to re-download your layers if they change in the future. If you want your layers to re-download, simply remove your layers folder.
You should then be able to invoke functions as normal, and they're executed against the layers in your docker container.
There are 5 additional options available for Docker and Layer usage.
When running Docker Lambda inside another Docker container, you may need to configure the host name for the host machine to resolve networking issues between Docker Lambda and the host. Typically in such cases you would set this to host.docker.internal
.
When running Docker Lambda inside another Docker container, you may need to override the code path that gets mounted to the Docker Lambda container relative to the host machine. Typically in such cases you would set this to ${PWD}
.
When running Docker Lambda inside another Docker container, you may need to override network that Docker Lambda connects to in order to communicate with other containers.
For certain programming languages and frameworks, it's desirable to be able to write to the filesystem for things like testing with local SQLite databases, or other testing-only modifications. For this, you can set dockerReadOnly: false
, and this will allow local filesystem modifications. This does not strictly mimic AWS Lambda, as Lambda has a Read-Only filesystem, so this should be used as a last resort.
By default layers are downloaded on a per-project basis, however, if you want to share them across projects, you can download them to a common place. For example, layersDir: /tmp/layers
would allow them to be shared across projects. Make sure when using this setting that the directory you are writing layers to can be shared by docker.
As defined in the Serverless Documentation you can use API Keys as a simple authentication method.
Serverless-offline will emulate the behaviour of APIG and create a random token that's printed on the screen. With this token you can access your private methods adding x-api-key: generatedToken
to your request header. All api keys will share the same token.
Only custom authorizers are supported. Custom authorizers are executed before a Lambda function is executed and return an Error or a Policy document.
The Custom authorizer is passed an event
object as below:
1{ 2 "authorizationToken": "<Incoming bearer token>", 3 "methodArn": "arn:aws:execute-api:<Region id>:<Account id>:<API id>/<Stage>/<Method>/<Resource path>", 4 "type": "TOKEN" 5}
The methodArn
does not include the Account id or API id.
The plugin only supports retrieving Tokens from headers. You can configure the header as below:
1"authorizer": { 2 "authorizerResultTtlInSeconds": "0", 3 "identitySource": "method.request.header.Authorization", // or method.request.header.SomeOtherHeader 4 "type": "TOKEN" 5}
You are able to mock the response from remote authorizers by setting the environmental variable AUTHORIZER
before running sls offline start
Example:
Unix:
export AUTHORIZER='{"principalId": "123"}'
Windows:
SET AUTHORIZER='{"principalId": "123"}'
For HTTP APIs, JWT authorizers
defined in the serverless.yml
can be used to validate the token and scopes in the token. However at this time,
the signature of the JWT is not validated with the defined issuer. Since this is a security risk, this feature is
only enabled with the --ignoreJWTSignature
flag. Make sure to only set this flag for local development work.
If your authentication needs are custom and not satisfied by the existing capabilities of the Serverless offline project, you can inject your own authentication strategy. To inject a custom strategy for Lambda invocation, you define a custom variable under offline
called customAuthenticationProvider
in the serverless.yml file. The value of the custom variable will be used to require(your customAuthenticationProvider value)
where the location is expected to return a function with the following signature.
1offline: 2 customAuthenticationProvider: ./path/to/custom-authentication-provider
1// ./path/to/customer-authentication-provider.js 2 3module.exports = function (endpoint, functionKey, method, path) { 4 return { 5 getAuthenticateFunction() { 6 return { 7 async authenticate(request, h) { 8 // your implementation 9 }, 10 } 11 }, 12 13 name: "your strategy name", 14 scheme: "your scheme name", 15 } 16}
A working example of injecting a custom authorization provider can be found in the projects integration tests under the folder custom-authentication
.
You are able to use some custom headers in your request to gain more control over the requestContext object.
Header | Event key | Example |
---|---|---|
cognito-identity-id | event.requestContext.identity.cognitoIdentityId | |
cognito-authentication-provider | event.requestContext.identity.cognitoAuthenticationProvider | |
sls-offline-authorizer-override | event.requestContext.authorizer | { "iam": {"cognitoUser": { "amr": ["unauthenticated"], "identityId": "abc123" }}} |
By doing this you are now able to change those values using a custom header. This can help you with easier authentication or retrieving the userId from a cognitoAuthenticationProvider
value.
You are able to use environment variables to customize identity params in event context.
Environment Variable | Event key |
---|---|
SLS_COGNITO_IDENTITY_POOL_ID | event.requestContext.identity.cognitoIdentityPoolId |
SLS_ACCOUNT_ID | event.requestContext.identity.accountId |
SLS_COGNITO_IDENTITY_ID | event.requestContext.identity.cognitoIdentityId |
SLS_CALLER | event.requestContext.identity.caller |
SLS_API_KEY | event.requestContext.identity.apiKey |
SLS_API_KEY_ID | event.requestContext.identity.apiKeyId |
SLS_COGNITO_AUTHENTICATION_TYPE | event.requestContext.identity.cognitoAuthenticationType |
SLS_COGNITO_AUTHENTICATION_PROVIDER | event.requestContext.identity.cognitoAuthenticationProvider |
You can use serverless-dotenv-plugin to load environment variables from your .env
file.
You can supply response and request templates for each function. This is optional. To do so you will have to place function specific template files in the same directory as your function file and add the .req.vm extension to the template filename.
For example,
if your function is in code-file: helloworld.js
,
your response template should be in file: helloworld.res.vm
and your request template in file helloworld.req.vm
.
Consider this requestTemplate for a POST endpoint:
1"application/json": { 2 "payload": "$input.json('$')", 3 "id_json": "$input.json('$.id')", 4 "id_path": "$input.path('$').id" 5}
Now let's make a request with this body: { "id": 1 }
AWS parses the event as such:
1{ 2 "payload": { 3 "id": 1 4 }, 5 "id_json": 1, 6 "id_path": "1" // Notice the string 7}
Whereas Offline parses:
1{ 2 "payload": { 3 "id": 1 4 }, 5 "id_json": 1, 6 "id_path": 1 // Notice the number 7}
Accessing an attribute after using $input.path
will return a string on AWS (expect strings like "1"
or "true"
) but not with Offline (1
or true
).
You may find other differences.
For HTTP APIs, the CORS configuration will work out of the box. Any CLI arguments passed in will be ignored.
For REST APIs, if the endpoint config has CORS set to true, the plugin will use the CLI CORS options for the associated route. Otherwise, no CORS headers will be added.
Set greedy paths like /store/{proxy+}
that will intercept requests made to /store/list-products
, /store/add-product
, etc...
Works out of the box.
Works out of the box. See examples in the manual_test directory.
Serverless doc ~ AWS doc - AWS::ApiGateway::Method ~ AWS doc - AWS::ApiGateway::Resource
Example of enabling proxy:
1custom: 2 serverless-offline: 3 resourceRoutes: true
or
1 YourCloudFormationMethodId: 2 Properties: 3 ...... 4 Integration: 5 Type: HTTP_PROXY 6 Uri: 'https://s3-${self:custom.region}.amazonaws.com/${self:custom.yourBucketName}/{proxy}' 7 ...... 8 Type: AWS::ApiGateway::Method
1custom: 2 serverless-offline: 3 resourceRoutes: 4 YourCloudFormationMethodId: 5 Uri: "http://localhost:3001/assets/{proxy}"
You can set your response's headers using ResponseParameters.
May not work properly. Please PR. (Difficulty: hard?)
Example response velocity template:
1"responseParameters": { 2 "method.response.header.X-Powered-By": "Serverless", // a string 3 "method.response.header.Warning": "integration.response.body", // the whole response 4 "method.response.header.Location": "integration.response.body.some.key" // a pseudo JSON-path 5},
Usage in order to send messages back to clients:
POST http://localhost:3001/@connections/{connectionId}
Or,
1import aws from 'aws-sdk' 2 3const apiGatewayManagementApi = new aws.ApiGatewayManagementApi({ 4 apiVersion: '2018-11-29', 5 endpoint: 'http://localhost:3001', 6}); 7 8apiGatewayManagementApi.postToConnection({ 9 ConnectionId: ..., 10 Data: ..., 11});
Where the event
is received in the lambda handler function.
There's support for websocketsApiRouteSelectionExpression in it's basic form: $request.body.x.y.z
, where the default value is $request.body.action
.
Serverless offline plugin will respond to the overall framework settings and output additional information to the console in debug mode. In order to do this you will have to set the SLS_DEBUG
environmental variable. You can run the following in the command line to switch to debug mode execution.
Unix:
export SLS_DEBUG=*
Windows:
SET SLS_DEBUG=*
Interactive debugging is also possible for your project if you have installed the node-inspector module and chrome browser. You can then run the following command line inside your project's root.
Initial installation:
npm install -g node-inspector
For each debug run:
node-debug sls offline
The system will start in wait status. This will also automatically start the chrome browser and wait for you to set breakpoints for inspection. Set the breakpoints as needed and, then, click the play button for the debugging to continue.
Depending on the breakpoint, you may need to call the URL path for your function in separate browser window for your serverless function to be run and made available for debugging.
With newer versions of node (6.3+) the node inspector is already part of your node environment and you can take advantage of debugging inside your IDE with source-map support. Here is the example configuration to debug interactively with VSC. It has two steps.
Add a new launch configuration to VSC like this:
1{ 2 "cwd": "${workspaceFolder}", 3 "name": "Debug Serverless Offline", 4 "request": "launch", 5 "runtimeArgs": ["run", "debug"], 6 "runtimeExecutable": "npm", 7 "sourceMaps": true, 8 "type": "node" 9}
You will also need to add a debug
script reference in your package.json file
Add this to the scripts
section:
Unix/Mac:
"debug" : "export SLS_DEBUG=* && node --inspect /usr/local/bin/serverless offline"
Windows:
"debug": "SET SLS_DEBUG=* && node --inspect node_modules\\serverless\\bin\\serverless offline"
Example:
1.... 2"scripts": { 3 "debug" : "SET SLS_DEBUG=* && node --inspect node_modules\\serverless\\bin\\serverless offline" 4}
In VSC, you can, then, add breakpoints to your code. To start a debug sessions you can either start your script in package.json
by clicking the hovering debug intellisense icon or by going to your debug pane and selecting the Debug Serverless Offline configuration.
Lambda functions assume an IAM role during execution: the framework creates this role and set all the permission provided in the iamRoleStatements
section of serverless.yml
.
However, serverless offline makes use of your local AWS profile credentials to run the lambda functions and that might result in a different set of permissions. By default, the aws-sdk would load credentials for you default AWS profile specified in your configuration file.
You can change this profile directly in the code or by setting proper environment variables. Setting the AWS_PROFILE
environment variable before calling serverless
offline to a different profile would effectively change the credentials, e.g.
AWS_PROFILE=<profile> serverless offline
This plugin simulates API Gateway for many practical purposes, good enough for development - but is not a perfect simulator. Specifically, Lambda currently runs on Node.js v12.x, v14.x and v16.x (AWS Docs), whereas Offline runs on your own runtime where no memory limits are enforced.
When combining this plugin with other plugins there are a few things that you need to keep in mind.
You should run serverless offline start
instead of serverless offline
. The start
command fires the offline:start:init
and offline:start:end
lifecycle hooks which can be used by other plugins to process your code, add resources, perform cleanups, etc.
The order in which plugins are added to serverless.yml
is relevant.
Plugins are executed in order, so plugins that process your code or add resources should be added first so they are ready when this plugin starts.
For example:
1plugins: 2 - serverless-middleware # modifies some of your handler based on configuration 3 - serverless-webpack # package your javascript handlers using webpack 4 - serverless-dynamodb # adds a local dynamo db 5 - serverless-offline # runs last so your code has been pre-processed and dynamo is ready
That works because all those plugins listen to the offline:start:init
to do their processing.
Similarly they listen to offline:start:end
to perform cleanup (stop dynamo db, remove temporary files, etc).
This plugin was initially a fork of Nopik's Serverless-serve.
MIT
Yes, thank you! This plugin is community-driven, most of its features are from different authors. Please update the docs and tests and add your name to the package.json file. We try to follow Airbnb's JavaScript Style Guide.
The latest stable version of the package.
Stable Version
1
9.8/10
Summary
Incorrect Authorization in serverless-offline
Affected Versions
<= 8.0.0
Patched Versions
Reason
no dangerous workflow patterns detected
Reason
29 commit(s) and 11 issue activity found in the last 90 days -- score normalized to 10
Reason
packaging workflow detected
Details
Reason
license file detected
Details
Reason
binaries present in source code
Details
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
Found 3/27 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
39 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moreserverless-offline-scheduler
Serverless plugin to run scheduled lambdas with serverless offline
serverless-offline-local-authorizers-plugin
[Serverless](http://www.serverless.com) plugin for adding authorizers when developing and testing functions locally with [serverless-offline](https://github.com/dherault/serverless-offline).
serverless-offline-watcher
Run arbitrary commands when files are changed while running serverless-offline
@sailplane/logger
CloudWatch and serverless-offline friendly logger.