Joseph Astrahan
Joseph Astrahan

Reputation: 9072

Serverless Detect Running Locally

I am running a command like the following.

serverless invoke local --function twilio_incoming_call

When I run locally in my code I plan to detect this and instead of looking for POST variables look for a MOCK file I'll be giving it.

I don't know how to detect if I'm running serverless with this local command however.

How do you do this?

I looked around on the serverless website and could find lots of info about running in local but not detecting if you were in local.

Upvotes: 4

Views: 2791

Answers (3)

Noel Llevares
Noel Llevares

Reputation: 16037

If you're using AWS Lambda, it has some built-in environment variables. In the absence of those variables, then you can conclude that your function is running locally.

https://docs.aws.amazon.com/lambda/latest/dg/lambda-environment-variables.html

const isRunningLocally = !process.env.AWS_EXECUTION_ENV

This method works regardless of the framework you use whether you are using serverless, Apex UP, AWS SAM, etc.

Upvotes: 6

Brian Winant
Brian Winant

Reputation: 3035

You can also check what is in process.argv:

process.argv[1] will equal '/usr/local/bin/sls'

process.argv[2] will equal 'invoke'

process.argv[3] will equal 'local'

Upvotes: 1

Joseph Astrahan
Joseph Astrahan

Reputation: 9072

I found out the answer. process.env.IS_LOCAL will detect if you are running locally. Missed this on their website somehow...

Upvotes: 12

Related Questions