Adding a Session timeout in Django

Arno Pretorius
2 min readMay 29, 2022

How to implement a session timeout in your Django web application.

Why do we need a session timeout?

If your users are accessing your website from a public computer at an internet cafe or a library, then there is a chance that they may forget to log out. If that is the case, then what stops a stranger from accessing their profile and reading all their sensitive information.

What can also happen is the user may not click log out, but instead close their browser. Someone who has some wits about them could easily re-trace the previous user’s history and again play around with their profile.

So, how do we sort this out?

Step 1:

To install django-session-timeout type in the below command:

pip install django-session-timeout

Step 2:

Next, you must add the middleware for django-session-timeout, this can be inserted anywhere. The middleware is as follows:

# settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware' , 'django_session_timeout.middleware.SessionTimeoutMiddleware' , ]

Step 3:

Some useful configurations that you can include in your settings.py are as follows:

Session timeout expiry time:

The code below will render your session invalid after 30 minutes from the start of an activity.

To set the session timeout expiry time, simply use:

# settings.py SESSION_EXPIRE_SECONDS = 1800 # Expire after 30 minutes

Invalidate the session after the most recent/last activity:

# settings.py SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True

Re-direct users to another page:

After your session has expired, re-direct your users away to another page, it could be your home page perhaps, but anyway, here is how you would approach it:

# settings.py SESSION_TIMEOUT_REDIRECT = ‘redirect_url_/’ # Add your URL

Expire the session when the browser closes:

Many of your users WILL forget to log out of their account and instead will close the browser, be prepared for this, by adding this line:

# settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True 

Conclusion

Okay, so that’s that! You will now be able to handle your user’s sessions more efficiently and in a more secure manner.

A final note…

For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course — 2022

Originally published at https://www.cloudwithdjango.com on May 29, 2022.

--

--

Arno Pretorius

Hi, I’m Arno… I love cloud computing and django web development and I want to share my knowledge and experiences with you.