ASP Cookies

A cookie is a small piece of information that ASP stores on the visitor's own browser using Response.Cookies, and later reads back with Request.Cookies.

What Is a Cookie?

A cookie is a tiny text value that a web server asks a browser to hold onto. The browser stores it on the visitor's own computer and sends it back to the server with every later request to the same site. ASP uses cookies to remember small facts about a visitor, such as a chosen username or a display preference, between separate visits.

Writing a Cookie

<%
  ' Store the visitor's name in a cookie called "username"
  Response.Cookies("username") = "Priya"

  ' Keep this cookie around for 30 days instead of just this browser session
  Response.Cookies("username").Expires = DateAdd("d", 30, Now())
%>
Note: Cookies are sent as HTTP response headers, so Response.Cookies must be assigned before any HTML has been sent to the browser — in practice, near the very top of your .asp file, before any <html> output.

Reading a Cookie Back

Reading a Cookie

<%
  Dim strName
  strName = Request.Cookies("username")

  If strName = "" Then
    Response.Write "Welcome, stranger!"
  Else
    Response.Write "Welcome back, " & strName & "!"
  End If
%>
Note: Cookies live on the client, not the server, and belong to one specific browser on one specific machine. If the visitor switches browsers, uses a different computer, or clears their cookies, the cookie is gone and Request.Cookies simply returns an empty string.

Cookies With Multiple Values (Subkeys)

A single cookie can hold several related values, called subkeys, instead of you creating a separate cookie for every piece of data. This keeps related information bundled together under one cookie name.

Cookie Subkeys

<%
  Response.Cookies("visitor")("name") = "Arjun"
  Response.Cookies("visitor")("city") = "Pune"
  Response.Cookies("visitor").Expires = DateAdd("m", 1, Now())
%>

<%
  ' On a later page:
  Response.Write Request.Cookies("visitor")("name") & " from " & Request.Cookies("visitor")("city")
%>
Cookie TypeHow It's CreatedWhen It Disappears
Session cookieNo Expires property setAs soon as the browser window closes
Persistent cookieExpires set to a future dateOn that date, or when manually deleted
Note: Cookies are stored as plain text on the visitor's machine and are sent back to the server with every request, so never store passwords or other sensitive data in one. Most browsers also cap a single cookie's size around 4KB.

Exercise: ASP Cookies

How do you create a cookie on the visitor's browser in classic ASP?