Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS lambda serverless website session maintaining

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!

like image 786
Pano Avatar asked Jan 16 '17 01:01

Pano


People also ask

How do you maintain a session in AWS Lambda?

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.

Can Lambda store session state?

First of all Lambda is used as a stateless compute service. Therefore keeping session state in Lambda is not practical.

Can AWS Lambda run for more than 15 minutes?

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.

How long does AWS Lambda stay active?

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.


2 Answers

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/

like image 140
Santhosh Gandhe Avatar answered Sep 21 '22 09:09

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 ...
        });
    }
like image 37
chrphb Avatar answered Sep 19 '22 09:09

chrphb