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

Open
opened 2026-04-17 22:41:25 -05:00 by GiteaMirror · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/better-auth/better-auth/pull/5775
Author: @Ridhim-RR
Created: 11/5/2025
Status: 🔄 Open

Base: mainHead: feat/5728-add-last-used-to-organization


📝 Commits (10+)

  • a0f74d0 feat(session): persist additionalFields in cookie cache (fixes #5700)
  • 22330a2 chore: run biome format and lint fixes
  • 8d2c961 refactor(dateFormat) : refreshedSession date format issue resolved
  • ebc3aba chore:(biome format) : run biome format and lint fixes
  • 9d36bf9 feat: Add lastUsed field to Organization(#5728)
  • 321f413 Update packages/better-auth/src/api/routes/session-api.test.ts
  • 5650ff6 Merge branch 'canary' into feat/5728-add-last-used-to-organization
  • d94090a fix(types):TypeScript type errors in your codebase.
  • c0ef4b5 chore(biome format): formatting error from Biome
  • bbf11f5 fix: type errors, cookie cache parsing, and import fixes

📊 Changes

11 files changed (+506 additions, -6 deletions)

View changed files

📝 packages/better-auth/src/api/routes/session-api.test.ts (+2 -2)
📝 packages/better-auth/src/api/routes/sign-in.test.ts (+173 -0)
📝 packages/better-auth/src/plugins/organization/adapter.ts (+34 -0)
📝 packages/better-auth/src/plugins/organization/index.ts (+1 -0)
📝 packages/better-auth/src/plugins/organization/organization.test.ts (+10 -4)
📝 packages/better-auth/src/plugins/organization/organization.ts (+6 -0)
📝 packages/better-auth/src/plugins/organization/routes/crud-org.test.ts (+199 -0)
📝 packages/better-auth/src/plugins/organization/routes/crud-org.ts (+10 -0)
📝 packages/better-auth/src/plugins/organization/schema.ts (+5 -0)
packages/better-auth/src/plugins/organization/utils.ts (+65 -0)
📝 packages/cli/test/__snapshots__/schema-mysql-custom.prisma (+1 -0)

📄 Description

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. -->



















---

<sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
## 📋 Pull Request Information **Original PR:** https://github.com/better-auth/better-auth/pull/5775 **Author:** [@Ridhim-RR](https://github.com/Ridhim-RR) **Created:** 11/5/2025 **Status:** 🔄 Open **Base:** `main` ← **Head:** `feat/5728-add-last-used-to-organization` --- ### 📝 Commits (10+) - [`a0f74d0`](https://github.com/better-auth/better-auth/commit/a0f74d0ab94f415f0c64a4bacfc3f1150227f16b) feat(session): persist additionalFields in cookie cache (fixes #5700) - [`22330a2`](https://github.com/better-auth/better-auth/commit/22330a2bd503828191432f4924927599203cb748) chore: run biome format and lint fixes - [`8d2c961`](https://github.com/better-auth/better-auth/commit/8d2c96132acfcaec35e4da056be6f257b3199a45) refactor(dateFormat) : refreshedSession date format issue resolved - [`ebc3aba`](https://github.com/better-auth/better-auth/commit/ebc3aba555389863c4dca013c9426e2668a97e9e) chore:(biome format) : run biome format and lint fixes - [`9d36bf9`](https://github.com/better-auth/better-auth/commit/9d36bf9cb24ae19835d09a9f52132a500253fe3a) feat: Add lastUsed field to Organization(#5728) - [`321f413`](https://github.com/better-auth/better-auth/commit/321f4136e3f8fe4048dde679b8d5b36d8f535111) Update packages/better-auth/src/api/routes/session-api.test.ts - [`5650ff6`](https://github.com/better-auth/better-auth/commit/5650ff69076cd7a38d6445d291856796461af928) Merge branch 'canary' into feat/5728-add-last-used-to-organization - [`d94090a`](https://github.com/better-auth/better-auth/commit/d94090a7de521950494672dd689f5642947773de) fix(types):TypeScript type errors in your codebase. - [`c0ef4b5`](https://github.com/better-auth/better-auth/commit/c0ef4b5235c3ecc44c1acf34393bb3f3e8976da2) chore(biome format): formatting error from Biome - [`bbf11f5`](https://github.com/better-auth/better-auth/commit/bbf11f52c3ce4c39179fad8c5d6bdf2bc212dd42) fix: type errors, cookie cache parsing, and import fixes ### 📊 Changes **11 files changed** (+506 additions, -6 deletions) <details> <summary>View changed files</summary> 📝 `packages/better-auth/src/api/routes/session-api.test.ts` (+2 -2) 📝 `packages/better-auth/src/api/routes/sign-in.test.ts` (+173 -0) 📝 `packages/better-auth/src/plugins/organization/adapter.ts` (+34 -0) 📝 `packages/better-auth/src/plugins/organization/index.ts` (+1 -0) 📝 `packages/better-auth/src/plugins/organization/organization.test.ts` (+10 -4) 📝 `packages/better-auth/src/plugins/organization/organization.ts` (+6 -0) 📝 `packages/better-auth/src/plugins/organization/routes/crud-org.test.ts` (+199 -0) 📝 `packages/better-auth/src/plugins/organization/routes/crud-org.ts` (+10 -0) 📝 `packages/better-auth/src/plugins/organization/schema.ts` (+5 -0) ➕ `packages/better-auth/src/plugins/organization/utils.ts` (+65 -0) 📝 `packages/cli/test/__snapshots__/schema-mysql-custom.prisma` (+1 -0) </details> ### 📄 Description 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. --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
GiteaMirror added the pull-request label 2026-04-17 22:41:25 -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#31816