Glossary

What Is a ColdFusion Scope (Application Session and Request)?

Definition

A ColdFusion scope is a named container that stores variables for a specific lifetime and visibility within a CFML application. The three core scopes developers use most are the Application, Session, and Request scopes. In simple terms:

  • The Application scope holds data shared by all users for the life of your application.
  • The Session scope holds data for one user across multiple requests during their visit.
  • The Request scope holds data only while processing a single HTTP request.

Each scope helps manage state, control Variable lifetime, and keep code organized and performant.


How It Works

What is a Scope in CFML?

A scope is a dictionary-like structure (a struct) available under a reserved name (e.g., application, session, request). ColdFusion automatically creates and destroys these scopes according to context and Configuration. You access variables using dot notation, such as application.settings or session.user.

Key idea: Use the right scope for the right lifetime. This avoids memory bloat, Race conditions, and accidental variable collisions.

Application scope

  • Lifetime: Starts when the application initializes; ends when the server restarts, application times out, or application is reloaded.
  • Visibility: Shared across all sessions and requests within the same application.
  • Typical contents: Configuration, caches, DAO/service singletons, lookup tables, feature flags.
  • Access: application.someKey

Because the Application scope is shared, it can be accessed concurrently. Protect mutable data with locking or use thread-safe structures.

Session Scope

  • Lifetime: Per-user across multiple requests until session timeout or explicit logout.
  • Visibility: Only available to the single user/session.
  • Typical contents: Authenticated user profile, permissions, preferences, shopping cart, CSRF tokens.
  • Access: session.user, session.cart
See also  What Is CFModule in ColdFusion?

ColdFusion supports standard cookie-based sessions and J2EE-style sessions. Enable Session management in Application.cfc for availability.

Request Scope

  • Lifetime: Only for the current HTTP request; destroyed when the request finishes.
  • Visibility: Available throughout processing of the current page, includes, and Custom tags.
  • Typical contents: View data, form processing results, transient variables, logging context.
  • Access: request.context, request.pageTitle

Use the Request scope to pass data between layers during one request without polluting broader scopes.

Other Related Scopes

  • variables / local / arguments: Function-level or component-level scopes; not shared across users. Use local/arguments for function variables to avoid accidental leakage.
  • server: Server-wide values (shared across all applications); use sparingly and safely.
  • client: Data stored on client or in a client store; rarely preferred over session due to Performance and storage implications.

Lifecycle and Order of Events

A typical lifecycle when Application.cfc is present:

  1. onApplicationStart() — Runs once when application starts; initialize application-wide resources.
  2. onSessionStart() — Runs when a new session is created.
  3. onRequestStart(targetPage) — Runs at the start of each request; good place for auth checks.
  4. onRequest(targetPage) — Executes the requested template.
  5. onRequestEnd() — Cleanup at the end of each request.
  6. onSessionEnd(sessionScope, appScope) — Runs when a session expires.
  7. onApplicationEnd(appScope) — Runs when the application shuts down.

This event sequence defines when scopes come into existence and when they can be safely used.


Syntax and Code Examples

Declaring Application and Session management

Application.cfc:


component {

this.name = “MyApp”;
this.applicationTimeout = createTimeSpan(0, 2, 0, 0); // 2 hours
this.sessionManagement = true;
this.sessionTimeout = createTimeSpan(0, 0, 30, 0); // 30 minutes
this.setClientCookies = true; // or manage your own cookies for J2EE sessions
// this.sessionType = “j2ee”; // optional: switch to J2EE-style sessions

function onApplicationStart() {
application.config = {
dbDsn = “MyDSN”,
featureX = true
};
application.services = {
userService = new com.services.UserService()
};
return true;
}

function onSessionStart() {
session.csrfToken = createUUID();
}

function onRequestStart(targetPage) {
// e.g., attach a per-request context
request.context = {
requestId = createUUID(),
startTick = getTickCount()
};
}

function onRequestEnd() {
// e.g., simple timing
request.context.durationMs = getTickCount() – request.context.startTick;
}
}

Working with Application Scope Safely

Storing a cached lookup:


if (!structKeyExists(application, “countryCache”)) {
// Avoid double-init in concurrent traffic
cflock type=”exclusive” timeout=”5″ scope=”application” {
if (!structKeyExists(application, “countryCache”)) {
application.countryCache = application.services.userService.loadCountries();
}
}
}

Note the exclusive cflock ensures only one request populates application.countryCache.

Using Session Scope for Auth

On login:


session.user = {
id = qUser.id,
email = qUser.email,
roles = listToArray(qUser.roles)
};

On logout:


structDelete(session, “user”);
sessionInvalidate(); // ends the session

See also  What Is CFTHREAD in ColdFusion?

Using Request Scope to Pass View Data


request.view = {};
request.view.pageTitle = “Dashboard”;
request.view.notifications = application.services.userService.getAlerts(session.user.id);

Then in your view:

#htmlEditFormat(request.view.pageTitle)#


Use Cases

Application Scope Use Cases

  • Caching reference data (countries, currencies, tax rates)
  • Sharing configuration across all users
  • Housing singletons (service objects) and connection pools

Session Scope Use Cases

  • Signed-in user information and authorization state
  • Shopping carts and wizard progress
  • Per-user feature flags and UI preferences

Request Scope Use Cases

  • Controller-to-view data transfer
  • Request-level logging and correlation IDs
  • Temporary processing buffers and error messages

Real-World Example: Multi-tenant SaaS Portal

  • Application scope: Load tenant configurations and service singletons once; e.g., application.tenants and application.services.billing.
  • Session scope: Store the authenticated user and tenantId: session.user and session.tenantId; track permissions and CSRF tokens.
  • Request scope: Build a request.context containing requestId, timing info, and viewData; pass to views and log sinks.

Flow:

  1. onApplicationStart loads tenant metadata into application.tenants.
  2. User logs in; session.user and session.tenantId are set.
  3. Each request populates request.context and request.view with the current tenant’s branding and menus.
  4. onRequestEnd logs duration using request.context.durationMs.

This approach separates concerns, improves Performance via caching, and maintains clean boundaries between lifetimes.


Comparison: Application vs Session vs Request

Aspect Application Session Request
Lifetime Entire app lifetime One user’s visit until timeout Single HTTP request
Visibility All users Single user Current request only
Typical Data Config, caches, services User profile, cart, preferences View data, transient context
Concurrency Risk High (shared) Medium (per user) Low (per request)
Example Access application.config session.user request.view

Best practices

  • Prefer the smallest scope that fits the need: request > session > application.
  • Keep Application data immutable where possible; if mutable, protect writes with cflock or use thread-safe constructs.
  • Avoid storing large objects (huge queries, big JSON) in session; use IDs and fetch when needed.
  • Keep session timeout reasonable (e.g., 15–30 minutes of inactivity); set applicationTimeout to match operations.
  • Initialize global resources in onApplicationStart; initialize per-user defaults in onSessionStart.
  • Store only safe data in cookies; consider this.sessionType = “j2ee” for more secure session handling.
  • Use request scope to carry view models and tracing information; do not leak into broader scopes.
  • Namespacing: group related keys, e.g., session.user, session.Security.csrfToken, application.cache.countries.

Security Considerations

  • Prevent session fixation: regenerate session identifiers on login; if using J2EE sessions, force a new session at auth time.
  • Use CSRF tokens stored per session and validated per request.
  • Do not store secrets in Application scope unless access is controlled and encrypted where necessary.
  • Use HTTPS and secure cookies; set httpOnly and secure flags.
  • Implement server-side authorization checks on every request, ideally in onRequestStart.
  • For clusters, ensure session stickiness or use a session store compatible with your CF engine (e.g., J2EE replication, database, or external stores). Verify consistency of Application scope initialization across nodes.
See also  What Is a ColdFusion Persistent Component?

Key Points

  • Application = shared, long-lived, excellent for caching and singletons, but requires concurrency safety.
  • Session = per-user state across requests; ideal for auth and preferences; keep it slim.
  • Request = ephemeral, best for view models and transient context; safest scope to use broadly.
  • Scopes are just structs; treat them like shared or private memory depending on lifetime.
  • Managing scope boundaries well yields better performance, fewer bugs, and clearer Architecture.

Common pitfalls

  • Writing to Application scope without locking, causing Race conditions.
  • Overloading Session with large queries or binary data, leading to memory pressure.
  • Using variables scope for shared data, causing hard-to-debug leaks; use Application/Session explicitly.
  • Forgetting to invalidate sessions on logout or privilege change.
  • Mutating Request scope late and expecting it to persist beyond the request.

FAQ

How do I enable sessions in ColdFusion?

Enable session management in Application.cfc: set this.sessionManagement = true; optionally set this.sessionType = “j2ee” and this.sessionTimeout. Ensure cookies are allowed or manage JSESSIONID/CFID/CFTOKEN headers appropriately.

When should I use cflock with Application or Session scope?

Use cflock when multiple requests could write to the same scope keys. For Application scope, lock around initialization and mutations. For Session scope, lock if you might have concurrent requests from the same user (e.g., multiple tabs) updating the same data.

What is the difference between request scope and variables/local scopes?

Request scope is available across the entire request (including includes), while variables/local are confined to specific components or functions. local/arguments are safest for function variables; request is for cross-file data sharing within a single request.

Can I store queries in session or application?

Yes, but use caution. Prefer caching in Application scope for read-mostly, small-to-medium lookup data. For large or dynamic data, store identifiers in Session and fetch on demand. Consider external caches or database caching for Scalability.

How do I reset the Application scope without restarting the server?

Change this.name in Application.cfc, manually call onApplicationStart() in a protected admin endpoint, or use administrative tooling. Ensure only authorized users can trigger an application reload.

About the author

Aaron Longnion

Aaron Longnion

Hey there! I'm Aaron Longnion — an Internet technologist, web software engineer, and ColdFusion expert with more than 24 years of experience. Over the years, I've had the privilege of working with some of the most exciting and fast-growing companies out there, including lynda.com, HomeAway, landsofamerica.com (CoStar Group), and Adobe.com.

I'm a full-stack developer at heart, but what really drives me is designing and building internet architectures that are highly scalable, cost-effective, and fault-tolerant — solutions built to handle rapid growth and stay ahead of the curve.