[PR #5775] Feat/5728 add last used to organization #14462

Open
opened 2026-04-13 09:29:11 -05:00 by GiteaMirror · 0 comments
Owner

Original Pull Request: https://github.com/better-auth/better-auth/pull/5775

State: open
Merged: No


Closes #5728

Feature: Add Last-Used Organization Tracking and Auto-Set on Sign-In

This PR addresses a common pain point for users belonging to multiple organizations by introducing native tracking and automatic restoration of the last-used organization upon sign-in.


🧩 Problem

When a user belongs to several organizations, the system currently does not remember which one they were last active in. This forces users to manually switch organizations every time they sign in, which is confusing and inefficient.

💡 Solution

We're implementing a robust mechanism to track and automatically restore the user's last active organization:

  • A new lastUsed field is added to the Organization schema to track the most recently active organization.
  • Automatic tracking is implemented when users switch organizations via setActiveOrganization.
  • A helper hook is provided to automatically find and set the last-used organization as active during the sign-in process.

🔧 Changes Made

Schema Changes

  • Added lastUsed: boolean field to the Organization schema (default: false).
  • Updated schema definition in organization.ts.

Core Functionality

  • setActiveOrganization Route (routes/crud-org.ts):
    • Sets lastUsed: true for the newly active organization.
    • Sets lastUsed: false for all other organizations belonging to the same user.
  • Organization Adapter:
    • Added findLastUsedOrganization method, which queries for the organization where lastUsed: true for the current user.

Helper Function

  • setLastUsedOrganizationAsActive (utils.ts):
    • A utility function designed for use in databaseHooks.session.create.after.
    • It automatically finds and sets the lastUsed organization as active in the session upon sign-in.
    • Exported from the organization plugin for easy integration.

Tests

  • Organization Switching Tests (crud-org.test.ts): Ensure the lastUsed flag is updated correctly when switching.
  • Sign-in Tests (sign-in.test.ts): Verify the automatic setting of the last-used organization on sign-in.

Database Migration Required ⚠️
This feature requires a mandatory database migration.

A new field has been introduced to the Organization schema to support the last-used tracking functionality. You must run a migration script against your database to add this column before deploying this update

⚙️ Usage

To enable the automatic restoration of the last-used organization on sign-in, integrate the provided helper function into your betterAuth configuration:

import { organization, setLastUsedOrganizationAsActive } from "better-auth/plugins/organization";

const orgPlugin = organization();

const auth = betterAuth({
  plugins: [orgPlugin],
  databaseHooks: {
    session: {
      create: {
        after: async (session, ctx) => {
          await setLastUsedOrganizationAsActive(session, ctx, orgPlugin.options);
        },
      },
    },















<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds last-used organization tracking and auto-restores it on sign-in to streamline multi-org workflows. Also fixes the session cookie cache to include additionalFields (Linear 5728).

- **New Features**
  - Added lastUsed boolean to the Organization schema (default false).
  - Updated setActiveOrganization to set lastUsed=true for the active org and false for others.
  - Added adapter.findLastUsedOrganization(userId) to fetch the users last-used org.
  - Introduced setLastUsedOrganizationAsActive helper to auto-activate the last-used org after sign-in.
  - Added tests for organization switching and sign-in auto-selection.

- **Migration**
  - Run a database migration to add the lastUsed field to organizations.
  - To enable auto-restore on sign-in, call setLastUsedOrganizationAsActive in databaseHooks.session.create.after.

<sup>Written for commit 5e95db9aea96ca42a7d5dbcbe7bed04e2b5f1257. Summary will update automatically on new commits.</sup>

<!-- End of auto-generated description by cubic. -->

















**Original Pull Request:** https://github.com/better-auth/better-auth/pull/5775 **State:** open **Merged:** No --- Closes #5728 # ✨ Feature: Add Last-Used Organization Tracking and Auto-Set on Sign-In This PR addresses a common pain point for users belonging to multiple organizations by introducing **native tracking and automatic restoration** of the last-used organization upon sign-in. --- ## 🧩 Problem When a user belongs to several organizations, the system currently **does not remember** which one they were last active in. This forces users to **manually switch organizations** every time they sign in, which is confusing and inefficient. ## 💡 Solution We're implementing a robust mechanism to track and automatically restore the user's last active organization: * A new `lastUsed` field is added to the Organization schema to track the most recently active organization. * Automatic tracking is implemented when users switch organizations via `setActiveOrganization`. * A helper hook is provided to automatically find and set the last-used organization as active during the sign-in process. --- ## 🔧 Changes Made ### Schema Changes * Added `lastUsed: boolean` field to the Organization schema (default: `false`). * Updated schema definition in `organization.ts`. ### Core Functionality * **`setActiveOrganization` Route (`routes/crud-org.ts`):** * Sets `lastUsed: true` for the newly active organization. * Sets `lastUsed: false` for all other organizations belonging to the same user. * **Organization Adapter:** * Added `findLastUsedOrganization` method, which queries for the organization where `lastUsed: true` for the current user. ### Helper Function * **`setLastUsedOrganizationAsActive` (`utils.ts`):** * A utility function designed for use in `databaseHooks.session.create.after`. * It automatically finds and sets the `lastUsed` organization as active in the session upon sign-in. * Exported from the organization plugin for easy integration. ### Tests * **Organization Switching Tests (`crud-org.test.ts`):** Ensure the `lastUsed` flag is updated correctly when switching. * **Sign-in Tests (`sign-in.test.ts`):** Verify the automatic setting of the last-used organization on sign-in. --- **Database Migration Required ⚠️** This feature requires a mandatory database migration. A new field has been introduced to the Organization schema to support the last-used tracking functionality. You must run a migration script against your database to add this column before deploying this update ## ⚙️ Usage To enable the automatic restoration of the last-used organization on sign-in, integrate the provided helper function into your `betterAuth` configuration: ```typescript import { organization, setLastUsedOrganizationAsActive } from "better-auth/plugins/organization"; const orgPlugin = organization(); const auth = betterAuth({ plugins: [orgPlugin], databaseHooks: { session: { create: { after: async (session, ctx) => { await setLastUsedOrganizationAsActive(session, ctx, orgPlugin.options); }, }, }, <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Adds last-used organization tracking and auto-restores it on sign-in to streamline multi-org workflows. Also fixes the session cookie cache to include additionalFields (Linear 5728). - **New Features** - Added lastUsed boolean to the Organization schema (default false). - Updated setActiveOrganization to set lastUsed=true for the active org and false for others. - Added adapter.findLastUsedOrganization(userId) to fetch the user’s last-used org. - Introduced setLastUsedOrganizationAsActive helper to auto-activate the last-used org after sign-in. - Added tests for organization switching and sign-in auto-selection. - **Migration** - Run a database migration to add the lastUsed field to organizations. - To enable auto-restore on sign-in, call setLastUsedOrganizationAsActive in databaseHooks.session.create.after. <sup>Written for commit 5e95db9aea96ca42a7d5dbcbe7bed04e2b5f1257. Summary will update automatically on new commits.</sup> <!-- End of auto-generated description by cubic. -->
GiteaMirror added the pull-request label 2026-04-13 09:29:11 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#14462