Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to aws-lambda context when running nodejs + expressjs

I'm, just starting out with AWS-Lambda, AWS-API Gateway and ExpressJs. I'm having trouble finding how the AWS-Lambda "context" is available in my "ExpressJs" application.

I'm using:

  • AWS-Lambda
  • AWS-API Gateway
  • NodeJs v4.3.2
  • ExpressJs 4.14.1
  • ClaudiaJs 2.7.0

In Aws Lambda I use aws-serverless-express to receive the API-Gateway request and initialize the node application. The following is the structure I have found from different tutorials, etc

lambda.js (Initiated from API-Gateway. Supplying the "context" variable in the call to "app.js")

'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const server = awsServerlessExpress.createServer(app)
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context)

The core of my app.js express is:

var express = require('express');
...
var app = express();
...
app.use('/', index);
...
module.exports = app;

My questions:

  1. Is there a way to access the AWS-Lambda "context" with this structure?
  2. If not, what would be the best "pattern" to make it available?

Any input appreciated.

like image 429
Koniak Avatar asked Feb 24 '17 10:02

Koniak


People also ask

Can I access the infrastructure that AWS Lambda runs on?

Q: Can I access the infrastructure that AWS Lambda runs on? No. AWS Lambda operates the compute infrastructure on your behalf, allowing it to perform health checks, apply security patches, and do other routine maintenance.

Does AWS Lambda support node JS?

AWS Lambda now supports Node. js 16 as both a managed runtime and a container base image. Developers creating serverless applications in Lambda with Node. js 16 can take advantage of new features such as support for Apple silicon for local development, the timers promises API, and enhanced performance.

Should I use Express with AWS Lambda?

Using Express. js in a lambda is not a good idea for many reasons: You will pay more for the execution of your Lambda because it will take more time to run and maybe more memory. Latency is higher.


1 Answers

You need to add middleware included in the aws-serverless-express package which exposes the event and context objects. You add it like this:

const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
app.use(awsServerlessExpressMiddleware.eventContext())

Once this middleware is configured the event and context objects will be added to the request. You access those objects like so:

var event = req.apiGateway.event;
var context = req.apiGateway.context;
like image 180
Mark B Avatar answered Sep 27 '22 22:09

Mark B