I developed a website using node.js as back-end. Recently I am trying to make it serverless and deploy to lambda. I will re-write most of my code but just haven't figured out how to maintain the session after user logged in. I was using "express-session" module and the session data is all recorded in the database.
To be honest I don't have a very deep understanding on sessions. I searched on google and did not find what I need. Does anyone have some sample code on maintaining sessions using lambda? or any resources. Thanks a lot!
There are multiple mechanisms available in HTTP to maintain session state within web applications, such as cookies (standard HTTP header), URL parameters, URL arguments on GET requests, body arguments on POST requests, such as hidden form fields (HTML forms), or proprietary HTTP headers.
First of all Lambda is used as a stateless compute service. Therefore keeping session state in Lambda is not practical.
Q: How long can an AWS Lambda function execute? AWS Lambda functions can be configured to run up to 15 minutes per execution. You can set the timeout to any value between 1 second and 15 minutes.
AWS Lambda only allows a maximum of 15 mins runtime before the function times out and the container dies, confining all un-persisted work (and running computations) to the graveyard of dead containers never to be restarted.
Either you use Cognito or your own way of session management, beware that lambda calls share their runtime and share static state between them. Make sure that your design considers this fact and architect your session sharing accordingly.
https://www.linkedin.com/pulse/does-lambda-call-share-any-commonstate-santhosh-gandhe/
In the Amazon Cognito Identity SDK for Javascript, check in particular the use case 16, it shows how to retrieve the Cognito current user. You can use this function to pass from page to page the current user attributes.
var poolData = {
UserPoolId : '...', // Your user pool id here
ClientId : '...' // Your client id here
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
alert(err);
return;
}
console.log('session validity: ' + session.isValid());
// other AWS actions ...
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With