Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

How does Phoenix scopes work?

Explanation of Phoenix 1.8 scopes pattern for centralizing user context and permission management for better security and maintainability

By Daniel Bergholz • Aug 20, 2025

The Phoenix team introduced “scopes” in Phoenix 1.8 as a recommended pattern (not a library) to improve security and maintainability by centralizing user context and permission management.

The Problem: Manual Parameter Passing

Traditional approach requires passing user-specific parameters (user ID, org ID, etc.) to every context function, which becomes unmanageable as complexity grows.

The Scope Solution

A scope is a struct containing all user context:

  • User ID, roles, permissions
  • Organization/team associations
  • Any other permission-related data

Instead of multiple parameters, pass one scope struct as the first parameter to context functions.

Implementation Pattern

  1. On Authentication: Build scope struct with user data in plugs
  2. In Controllers/Contexts: Pass scope as first parameter
  3. Pattern Matching: Authenticated users get full access, unauthenticated get public data only

Key Benefits

  • Centralized Security: All permission logic in one place
  • Maintainable: Adding new context (like organizations) only requires updating the scope
  • Secure by Default: Explicit permission checking prevents data leaks
  • Scalable: Pattern works well as apps grow more complex

Use Cases

  • Authenticated users see full profiles; unauthenticated see public profiles only
  • Multi-tenant applications with organization-based data filtering
  • Role-based access control across different resources

The Phoenix team highly recommends this pattern for any app handling user-specific data, making permission management simpler and more secure as complexity increases.

Related

#daniel-bergholz #phoenix-and-elixir

Related Content

CanCan vs Phoenix Scopes

By Jeffrey HicksAug 20, 2025

Perplexity research exploring the differences between CanCan's accessible_by method in Rails and Phoenix Scopes for authorization patterns

#phoenix-and-elixir#daniel-bergholz#phoenix-scopes-how-it-works