How to make session persistent in Actix-web?

Hello

Currently I am using

App::new()
           //...
            .wrap(
                SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
                    .cookie_secure(false)
                    .build(),
            )
           //...

To use Sessions in Actix-web. But I'd like to make these sessions persistent so the user stays logged in. Especially in my PWA. How would I do this?

1 Like

Cookie sessions persist as long as the cookie lives on the client. If you want to store session data that sticks between log ins to the same account, you'll need to save the data somewhere. actix_session lists a couple Redis options in its docs, but if you want to use another storage method you can always implement SessionStore yourself

3 Likes

Can't I just configure a TTL parameter somewhere in CookieSessionStore?

Or would implementing Redis also keep my user logged in? But how would an in-memory database like Redis work? How can the client-side remember what row it belongs to on the server-side?

You can add .session_lifecycle(PersistentSession::default().session_ttl(session_ttl)) before the .build() it seems. session_ttl here is a time::Duration.

3 Likes

This works perfectly.

SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
                    .cookie_secure(false)
                    .session_lifecycle(
                        PersistentSession::default()
                            .session_ttl(actix_web::cookie::time::Duration::weeks(2)),
                    )
                    .build(),
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.