ASP Session Variables

Session variables let ASP store data on the server for one specific visitor, and that data stays available across every page the visitor requests until their session ends.

What Is a Session?

When a visitor first requests a page from an ASP application, the server creates a Session object just for them and assigns it a unique Session ID. That ID is sent to the browser as a single small cookie. On every later request, the browser sends the ID back, and ASP uses it to look up that visitor's own private storage area on the server, called Session variables.

Storing a Session Variable

<%
  Session("username") = "Priya"
  Session("cartTotal") = 0
%>

Reading a Session Variable on Another Page

Example

<%
  If Session("username") <> "" Then
    Response.Write "Hello, " & Session("username") & "!"
  Else
    Response.Write "Please log in first."
  End If
%>

Cookies vs. Session Variables

It is easy to confuse cookies and Session variables because a Session relies on a cookie behind the scenes, but the two store data very differently. A cookie stores the actual data on the visitor's browser. A Session variable stores the actual data on the server; the browser only ever holds a small session ID cookie pointing to that server-side storage.

CookiesSession Variables
Where the data livesClient (the visitor's browser)Server (in memory, per visitor)
What the browser storesThe full value you assignedOnly a Session ID
Typical lifetimeUntil it expires or is deletedUntil Session.Timeout minutes of inactivity, or Session.Abandon
Visible to the visitorYes, viewable/editable in browser dev toolsNo, it never leaves the server

Controlling How Long a Session Lasts

By default, IIS ends a session after 20 minutes without a new request from that visitor, freeing the server memory it used. You can change this per session with Session.Timeout, measured in minutes, and end a session immediately with Session.Abandon.

Session Timeout and Abandon

<%
  ' Keep this visitor's session alive for 45 minutes of inactivity
  Session.Timeout = 45
%>

<%
  ' On a logout page, end the session right away
  Session.Abandon
  Response.Redirect "login.asp"
%>
Note: Session.Abandon does not clear the variables instantly inside the current page; it just marks the session to be destroyed once the page finishes running, so set them to empty strings first if you need them gone immediately. Also note that if a visitor has disabled cookies entirely, the Session ID cookie can't be stored, and ASP starts a brand-new session on every request — so Session variables will appear to reset on every page.

Exercise: ASP Session

What is the scope of a Session variable?