39

I used to heavily rely on session variables in the past, but have recently found many of them to be unnecessary, using things like query string parameters instead.

A colleague of mine refuses to use session variables. Is this a realistic goal and should session variables be avoided for any practical reasons? Can session variables be avoided completely (except for session cookies to allow logins) and would this result in better designs?

Some of the reasons my colleague has for not using them:

  • Untyped nature of session variables
  • Session time-outs causing loss of state
  • Global scope nature of session variables
  • Load balancing servers losing sessions (.Net specific?)
  • Application pools/servers restarting
  • They are unnecessary
4
  • 3
    using things like query string parameters instead - With this one case, always always use the query string parameters if possible. Using session for that type of parameter is fragile and can introduce strange bugs when users have multiple tabs open.
    – Izkata
    Aug 15, 2012 at 18:25
  • 2
    personal recommendation - dont take any advice from your colleague as he clearly doesnt know what he's talking about. Session timeouts? Does he not realize session durations are controlled by the web app? Aug 15, 2012 at 19:04
  • 2
    @GrandmasterB Ahem. Either doesn't know what they're doing or has been burned by each one of those bullet points over the course of their career (I myself have hit about 4 of them) and knows more appropriate ways to deal with temporary state.
    – Ed James
    Aug 16, 2012 at 9:24
  • Could someone please explain the relationship between session state and having multiple tabs open? When you open a new tab, does it or does it now contain the state from the previous tab? Thanks.
    – Jim
    Oct 24, 2015 at 23:12

6 Answers 6

44

If you have a session variable in your application, ask yourself this:

When I click the back button of my browser, what value do I want my variable to have?

If the answer is "the current value", session variables may be useful. An example would be a shopping cart: you don't expect things to be removed from the shopping cart as you go back through the history. It's always in its current state.

If the answer is "a previous value", you should not be using session variables. Bad uses I have seen include passing a parameter between pages. If I click the back button to get back to a page, the page does not necessarily get the correct parameter. Also, if I open two tabs, how is my site going to behave then?

Getting the back button behaviour right is by no means the be-all-and-end-all, but it helps you think about a web site as a stateless application. In general, I find appropriate uses of session variables to be few and far between.

3
  • I agree. Once you think about the desired semantics with multiple tabs it usually becomes obvious if session variables or request parameters are the right choice. Aug 15, 2012 at 21:37
  • I have seen exactly these types of errors with session variables, and admittedly learned the hard way myself.
    – Tjaart
    Aug 16, 2012 at 6:22
  • When a user hits the back button, do they expect the items to stay in the shopping cart until their session expires or do they want the items to stay til they are taken out? Using some other persistence mechanism (like a database) would allow for persistence beyond the single session and your back button would still function as the user expected. Oct 30, 2014 at 17:41
26

The HTTP protocol is stateless. Sessions are a way to preserve client state across HTTP requests. You may choose to do that with a platform's built-in session handling or do it yourself with query string parameters. Either way some concept of a session is necessary for many tasks.

Your colleague probably dislikes a specific implementation, or hasn't been using sessions for their intended purposes. If you need to retain information about a specific client connection across HTTP requests, you need some form of session persistence.

The following issues are implementation specific:

Untyped nature of session variables

Global scope nature of session variables

Load balancing servers losing sessions

Application pools/servers restarting

For example, I most often work in PHP and store my session information in a relational database. So my session variables are typed. Load balancing and server restarts don't cause any session issues.

This one is more interesting:

Session time-outs causing loss of state

Sessions are most often preserved via cookies. These can be deleted by the client at any time. But they can also be preserved via a query string parameter and therefore never time out on the client. The server timeout is up to you. So even this issue is implementation specific.

Let's not throw out the entire concept of sessions just because we don't like a particular implementation. Any good web application framework will facilitate using sessions properly to preserve user logins or retain anything else specific to the user's current visit. A user's database record can (and should) be used to store things specific to them when logged in. Anonymous visitors, however, may have temporary information also worth preserving in their session, such as a short list of recent pages visited or the preference to hide a notice they've already seen. Generally only smaller temporary information is appropriate for session storage.

3
  • To be honest I have had limited experience with frameworks besides .Net. .Net stops short of forcing a time-out value for your sessions. Session variables also bubble up to server side code as an untyped dictionary. I usually wrap this dictionary in properly typed classes anyway, so I don't see this as a problem either. You mentioned that you store your session information in the database. In ASP .Net the storage is dealt with otherwise, either in the .Net client, in the database (automatically managed) or in a separate windows service.
    – Tjaart
    Aug 15, 2012 at 14:27
  • Can you give some examples of intended purposes for sessions?
    – Tjaart
    Aug 15, 2012 at 14:30
  • @Tjaart: I expanded the last paragraph a bit. Hope that helps.
    – Matt S
    Aug 15, 2012 at 14:45
15

Others have made a lot of good points (which I will avoid repeating), but there is one aspect of your buddy's technique that has not been discussed yet: security.

Its impossible to know what kind of vulnerabilities you open up without looking at the code, but here's a few things I can think of off the top of my head.

  • Session fixation: A powerful attack that is slightly easier if you can just have the user click a link that already has the necessary info in the URL (rather than trying to get the user to use a machine that has its cookies appropriately set).
  • SQL injection (or other malicious input): Never trust anything that comes from the user. Session variables have an advantage of never leaving the server, thus the user cannot directly change them. While you should sanitize data before putting it into the session, you can always trust the values you get out afterwards. If everything is passed around through the query string, you have a LOT of validating you need to do to make sure that you're not accepting malicious input.
  • Corrupting data by using falsified inputs: Similar to SQL injection, how much data are you passing back and forth? How crucial is it? Can I change the behavior of your app by changing a value in the query string? Can I corrupt the data on your server by changing values? If I manage to corrupt the data on the server, will it affect other users? (If your answer was "no", my response is "are you sure? You have a lot of places you need to check.").

All of these can still happen when you use Sessions, but they can get a lot easier if your buddy doesn't know what he's doing.

0
2

Session variables are like the old Basic global variables to some degree. The burden is on the user to keep track of them, what's in them, their scope and how they are used; just like in old versions of BASIC. That being said, why would someone totally discount the use of a mechanism that is obviously designed to be an integral and very importaint part of the programming model (ASP, MVC etc.)?

The only bad thing that I've run into in using Session variables is that it puts the burden on you to keep track of them, make sure they are populated with relavent data and disposing of them.

Isn't that what we do when we are programming any way?

1

I used to think like your colleague due to some bad experiences I'd had debugging issues related to session variables, which were really just incompetence on my part. Yes you can get by to some extent without session variables, using query strings, hidden fields in forms and other things. However it very quickly gets cumbersome to do it this way if your application has anything beyond the most basic logic flow to determine state. There's also the security risk of showing the inner workings of your application via query strings and hidden fields, any of which can serve as attack vectors.

When working with session variables you just need to keep track of when they get set and unset, as this will determine the logic flow of the application. It's like memory management in a language like C.

Note that this is just from my experience working with PHP on a relatively small project with no frameworks, things may be different on other platforms but I think the general principle still applies.

3
  • 2
    How do you get multiple tab semantics right when using sessions for state involved in your control flow? Sessions work well for login and settings like properties, but they don't have the right semantics for most other uses. Aug 15, 2012 at 21:39
  • I'm not sure, what I posted was based on my own admittedly limited experience building a database driven web app in PHP/MySQL. How are multiple tabs in browsers typically handled (I'm assuming that's what you're referring to)? Aug 16, 2012 at 13:05
  • @primehunter326 With route params or query strings or hidden form fields.
    – Casey
    Mar 21, 2018 at 18:31
0

As previously stated HTTP is Stateless and Session Variable break that. HTTP design to be stateless helps caching of resources. For resources that are publicly available.

It's possible to design a website without session variable but it's harder. The hardest (IMHO) is the fancy login/logout, HTTP authentication schemes does not provide the tools needed to authenticate via an HTML form (you might hack something with javascript - XHR to https://untel:[email protected]) and it's even harder to logout and be cross browser compatible. there was some discussion the w3 mailling lists about that but if I remember correctly the idea was dropped.

For the rest, you should be able to live without Session variables. You will have some state on a database, files or anywhere but the use for Session variables should be rare.

If your user have a shopping cart, it's a variable session only if the user is supposed to be able to browse on two computer/browser without sharing the cart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.