Skip to content

Conversation

@dtoxvanilla1991
Copy link

Remove the deprecated @kinde-oss/kinde-typescript-sdk and integrate @kinde/js-utils for improved session management. Update session methods and TypeScript definitions to streamline the Kinde setup process.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 20, 2025

Walkthrough

Initialisation now runs session setup before creating the internal client; session management was refactored to use an ExpressSessionManager per request, setup modules were converted to pure re-exports, Express request session typings were simplified, Vite marks @kinde/js-utils external, and tests for session behavior were added.

Changes

Cohort / File(s) Change Summary
Public entry / bootstrap
src/index.ts
Calls setupKindeSession(app) before creating the internal client; reorganized imports; removed previously exported SDK items so only jwtVerify remains exported; updated doc/comments and altered initialization order.
Setup re-exports
src/setup/index.ts
Converted to a pure re-export surface: re-exports getInternalClient, getInitialConfig, setupInternalClient (from kindeClient.js), and getSessionManager, setupKindeSession (from sessionManager.js); removed local composite setupInternalClient implementation.
Session manager implementation
src/setup/sessionManager.ts
Exported getSessionManager; replaced inline per-request functions with creating an ExpressSessionManager instance per request and binding its async methods (setSessionItem, getSessionItem, removeSessionItem, destroySession) onto req; added try/catch and next(err) forwarding.
Express request/session types
src/types/express-session.d.ts
Removed external type imports and prior SessionManager inheritance; simplified session to an optional index-signature + destroy callback; added optional async session methods (setSessionItem, getSessionItem, removeSessionItem) and destroySession; added export {}.
Setup types
src/setup/kindeSetupTypes.ts
Added export to setup config interfaces and constrained SetupConfig<G> to G extends GrantType.
Tests: session manager
src/setup/sessionManager.test.ts
New tests validating setupKindeSession idempotency, that getSessionManager middleware is appended, and end-to-end behavior of attached session methods via HTTP routes (set/get/remove/destroy).
Mocks / imports
src/mocks.ts
Adjusted imports: GrantType now imported from @kinde-oss/kinde-typescript-sdk; setupKinde import split to ./index.js.
Build config
vite.config.ts
Added @kinde/js-utils to Rollup external list in Vite config.

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer
    participant App as Express App
    participant setupKinde as setupKinde (bootstrap)
    participant setupKindeSession as setupKindeSession
    participant Router as Express router / middleware stack
    participant getSessionManager as getSessionManager middleware
    participant ESMgr as ExpressSessionManager
    participant setupInternalClient as setupInternalClient

    Dev->>App: create app and call setupKinde(app, config)
    App->>setupKinde: initialize
    setupKinde->>setupKindeSession: setupKindeSession(app)
    setupKindeSession->>App: register session middleware (if missing)
    App->>Router: incoming request -> middleware chain
    Router->>getSessionManager: invoke getSessionManager middleware
    getSessionManager->>ESMgr: create ExpressSessionManager instance (per request)
    ESMgr-->>Router: bind async session methods onto req
    setupKinde->>setupInternalClient: setupInternalClient(config)
    setupInternalClient-->>App: internal client configured
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review session binding semantics in src/setup/sessionManager.ts — ensure method bindings and error forwarding match prior behavior.
  • Verify src/types/express-session.d.ts changes for downstream type compatibility.
  • Confirm src/index.ts export reductions (only jwtVerify) do not break public API expectations.
  • Check vite.config.ts externalization of @kinde/js-utils for intended bundling outcomes.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: replacing the deprecated SDK, integrating js-utils ExpressStore, and enhancing session management, which are the core objectives of the PR.
Description check ✅ Passed The description is directly related to the changeset, mentioning removal of deprecated SDK, integration of js-utils, and updates to session methods and TypeScript definitions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2e7c375 and c363d68.

⛔ Files ignored due to path filters (3)
  • package.json is excluded by !**/*.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
  • pnpm-workspace.yaml is excluded by !**/*.yaml
📒 Files selected for processing (8)
  • src/index.ts
  • src/mocks.ts
  • src/setup/index.ts
  • src/setup/kindeSetupTypes.ts
  • src/setup/sessionManager.test.ts
  • src/setup/sessionManager.ts
  • src/types/express-session.d.ts
  • vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • vite.config.ts
  • src/mocks.ts
  • src/setup/sessionManager.test.ts
  • src/setup/index.ts
  • src/setup/kindeSetupTypes.ts
  • src/types/express-session.d.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: DanielRivers
Repo: kinde-oss/kinde-node-express PR: 26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.
Learnt from: DanielRivers
Repo: kinde-oss/kinde-node-express PR: 26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-06-10T19:15:23.818Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.
📚 Learning: 2024-10-08T23:57:58.113Z
Learnt from: DanielRivers
Repo: kinde-oss/kinde-node-express PR: 26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.

Applied to files:

  • src/setup/sessionManager.ts
🧬 Code graph analysis (2)
src/index.ts (4)
src/setup/kindeSetupTypes.ts (1)
  • SetupConfig (41-47)
src/setup/index.ts (2)
  • setupKindeSession (9-9)
  • setupInternalClient (6-6)
src/setup/sessionManager.ts (1)
  • setupKindeSession (58-63)
src/setup/kindeClient.ts (1)
  • setupInternalClient (121-157)
src/setup/sessionManager.ts (2)
src/setup/index.ts (1)
  • getSessionManager (9-9)
src/utils.ts (1)
  • ExpressMiddleware (13-17)
🔇 Additional comments (7)
src/setup/sessionManager.ts (4)

21-27: LGTM! Documentation and export align with new architecture.

The updated JSDoc accurately describes the per-request ExpressSessionManager pattern, and exporting getSessionManager makes it available as a public API entry point (re-exported from src/setup/index.ts).


54-63: LGTM! Documentation update aligns with implementation.

The JSDoc correctly references the Kinde ExpressSessionManager, and the implementation properly ensures express-session is attached before getSessionManager middleware. The idempotency check via hasSessionMiddleware prevents duplicate session middleware registration.


4-4: The import statement references a non-existent class.

@kinde/js-utils latest version is 0.10.1, and this package does not export an ExpressSessionManager class. The @kinde-oss/kinde-typescript-sdk exports a SessionManager interface with methods getSessionItem, setSessionItem, removeSessionItem, and destroySession, but not an ExpressSessionManager class. This import statement needs correction—verify the correct package and class name from the Kinde documentation or package exports.


28-43: Excellent addition of error handling per previous review.

The try-catch wrapper properly addresses the prior review comment about silent failures. Error forwarding to next(error) follows Express middleware conventions.

Verify the per-request ExpressSessionManager instantiation pattern.

Creating a new ExpressSessionManager instance for every request may have performance implications. Session management typically requires a session store to track authenticated sessions between requests, with any key-value store used by implementing the SessionManager interface. Session managers are commonly a wrapper around an existing session management library, and standard Express middleware patterns suggest session managers are typically initialized once as singletons rather than per-request.

src/index.ts (3)

14-21: LGTM! Documentation accurately describes the new initialization flow.

The JSDoc clearly outlines the three-step process: session setup, client creation, and route attachment. This helps users understand the initialization sequence.


1-12: Import organization is correct; no breaking changes from export removals.

The new imports (setupKindeSession and type GrantType) are properly structured. GrantType is correctly imported as a type-only import and used as a generic constraint in the setupKinde function signature. The re-exports from ./helpers/index.js remain unchanged and export the public API methods (createOrg, getUser, protectRoute, jwtVerify).


22-33: The initialization order is correct, but the dependency reasoning needs adjustment.

The three-step setup (session → client → routes) is logically sound. However, setupInternalClient does not actually depend on session initialization—it only needs the configuration object and creates the Kinde client. The actual dependency is that setupAuthRouter requires setupInternalClient to run first, since the auth router calls getInternalClient() internally. Setting up the session first makes sense because requests will need session support when hitting auth routes, but this is not a technical requirement of setupInternalClient itself.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
src/setup/index.ts (1)

1-2: Fix typo in comment.

There's a typo in the comment: "teh" should be "the".

-// this file only re-exports the necessary functions and types from teh other files
+// this file only re-exports the necessary functions and types from the other files
src/setup/sessionManager.ts (3)

4-5: Remove duplicate express-session import.

The bare import of "express-session" on line 5 appears unnecessary since you're already importing the named exports on line 3.

-import {ExpressSessionManager} from '@kinde/js-utils';
-import "express-session";
+import {ExpressSessionManager} from '@kinde/js-utils';

23-24: Update comment to reflect actual package name.

The comment mentions "utils lib" but should reference the actual package name for clarity.

- * Sets up the session manager by creating an instance of our reusable
- * `ExpressSessionManager` class for each req.
+ * Sets up the session manager by creating an instance of the
+ * `ExpressSessionManager` class from @kinde/js-utils for each request.

52-52: Update comment to reflect the actual package name.

The comment should reference the correct package name for accuracy.

- * Attaches the `express-session` middleware and the Kinde ExpressSessionManager.
+ * Attaches the `express-session` middleware and the ExpressSessionManager from @kinde/js-utils.
src/index.ts (1)

14-14: Consider documenting the local union type.

The local KindeGrantType union type could benefit from a JSDoc comment explaining why it's defined locally instead of imported.

-// not sure for now what terminology to use here
+/**
+ * Local grant type definition for Kinde setup.
+ * Limited to the supported grant types for this Express integration.
+ */
 type KindeGrantType = "authorization_code" | "client_credentials";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c98d32 and d61af25.

⛔ Files ignored due to path filters (3)
  • package.json is excluded by !**/*.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
  • pnpm-workspace.yaml is excluded by !**/*.yaml
📒 Files selected for processing (5)
  • src/index.ts (1 hunks)
  • src/setup/index.ts (1 hunks)
  • src/setup/sessionManager.ts (3 hunks)
  • src/types/express-session.d.ts (1 hunks)
  • vite.config.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/setup/sessionManager.ts (2)
src/utils.ts (1)
  • ExpressMiddleware (13-17)
src/types/express-session.d.ts (1)
  • Request (17-22)
src/index.ts (3)
src/setup/index.ts (2)
  • setupKindeSession (9-9)
  • setupInternalClient (6-6)
src/setup/sessionManager.ts (1)
  • setupKindeSession (55-60)
src/setup/kindeClient.ts (1)
  • setupInternalClient (97-127)
🔇 Additional comments (5)
vite.config.ts (1)

9-9: LGTM! Correct external dependency addition.

Adding @kinde/js-utils to the external dependencies is appropriate since it's now being used in the session manager and should remain unbundled.

src/setup/index.ts (1)

3-10: Good separation of concerns.

Converting this file to a pure re-exporter improves modularity and makes the codebase easier to maintain.

src/index.ts (1)

24-35: Good separation of concerns in setup flow.

The sequential setup approach (session → client → routes) is logical and improves maintainability. The function signature simplification also makes the API cleaner.

Note: This change may be breaking for existing users who relied on the generic parameter, but the local union type maintains type safety while simplifying the API.

src/types/express-session.d.ts (2)

8-13: Simplified session interface is cleaner.

The simplified Request interface extension with optional session object is much cleaner than the previous approach.


16-23: Verify runtime availability of optional session methods.

The session methods are defined as optional properties on the Request interface. Ensure that code using these methods checks for their existence before calling them, since they're only available after the session manager middleware runs.

#!/bin/bash
# Description: Search for usage of session methods to verify proper existence checks
# Expected: Usage should include optional chaining or existence checks

echo "Searching for session method usage..."
rg -A 3 -B 1 "(setSessionItem|getSessionItem|removeSessionItem|destroySession)" --type ts

@dtoxvanilla1991 dtoxvanilla1991 marked this pull request as draft June 21, 2025 16:51
@dtoxvanilla1991 dtoxvanilla1991 marked this pull request as ready for review July 2, 2025 14:14
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/setup/kindeSetupTypes.ts (1)

50-56: Inconsistent migration: ClientOptions still uses deprecated GrantType.

Similar to ClientType, this type definition still uses the deprecated GrantType instead of the new KindeGrantType. This creates inconsistency in the migration.

Consider updating to use KindeGrantType:

-export type ClientOptions<G> = G extends GrantType.PKCE
+export type ClientOptions<G> = G extends KindeGrantType.PKCE
   ? PKCEClientOptions
-  : G extends GrantType.AUTHORIZATION_CODE
+  : G extends KindeGrantType.AUTHORIZATION_CODE
     ? ACClientOptions
-    : G extends GrantType.CLIENT_CREDENTIALS
+    : G extends KindeGrantType.CLIENT_CREDENTIALS
       ? CCClientOptions
       : never;
🧹 Nitpick comments (2)
src/setup/sessionManager.test.ts (2)

25-27: Consider avoiding access to Express private properties

The tests access app._router.stack which is a private property of Express. This approach could be brittle and may break with future Express updates.

Consider using a more robust testing approach:

-      const sessionMiddleware = app._router.stack.find(
-        (layer) => layer.name === 'session'
-      );
-      expect(sessionMiddleware).toBeDefined();
+      // Test middleware functionality instead of implementation details
+      const res = await request(app).get('/test-route');
+      expect(res.status).not.toBe(500); // Verify middleware doesn't cause errors

Also applies to: 35-43


84-91: Improve error handling specificity

The generic catch block doesn't provide specific error information, which could make debugging difficult.

Consider improving error handling:

-        } catch {
-          res.status(500).send('Error destroying session');
-        }
+        } catch (error) {
+          console.error('Session destruction failed:', error);
+          res.status(500).send('Error destroying session');
+        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d61af25 and 744c0ed.

📒 Files selected for processing (7)
  • src/index.ts (1 hunks)
  • src/mocks.ts (1 hunks)
  • src/setup/index.ts (1 hunks)
  • src/setup/kindeSetupTypes.ts (3 hunks)
  • src/setup/sessionManager.test.ts (1 hunks)
  • src/setup/sessionManager.ts (3 hunks)
  • src/types/express-session.d.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/mocks.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/index.ts
  • src/setup/index.ts
  • src/setup/sessionManager.ts
  • src/types/express-session.d.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: DanielRivers
PR: kinde-oss/kinde-node-express#26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-06-10T19:15:23.818Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.
Learnt from: DanielRivers
PR: kinde-oss/kinde-node-express#26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.
src/setup/sessionManager.test.ts (2)
Learnt from: DanielRivers
PR: kinde-oss/kinde-node-express#26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-06-10T19:15:23.818Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.
Learnt from: DanielRivers
PR: kinde-oss/kinde-node-express#26
File: src/setup/sessionManager.ts:10-10
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The session secret in `src/setup/sessionManager.ts` can be set via an environment variable `SESSION_SECRET`, with a fallback to a randomly generated string if the environment variable is not set. This ensures session persistence across server restarts unless the secret is not explicitly set.
🧬 Code Graph Analysis (1)
src/setup/sessionManager.test.ts (1)
src/setup/sessionManager.ts (1)
  • setupKindeSession (58-63)
🪛 ast-grep (0.38.1)
src/setup/sessionManager.test.ts

[warning] 32-32: A hard-coded credential was detected. It is not recommended to store credentials in source-code, as this risks secrets being leaked and used by either an internal or external malicious adversary. It is recommended to use environment variables to securely provide credentials or retrieve credentials from a secure vault or HSM (Hardware Security Module).
Context: secret: 'secret'
Note: [CWE-798] Use of Hard-coded Credentials. [REFERENCES]
- https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html

(express-session-hardcoded-secret-typescript)

🔇 Additional comments (10)
src/setup/sessionManager.test.ts (3)

1-12: LGTM: Clean import structure

The imports are well-organized and use proper TypeScript typing conventions.


105-112: Excellent session management test coverage

The tests comprehensively cover the ExpressSessionManager functionality including set, get, remove, and destroy operations. The use of request.agent() properly maintains session state across requests.

Also applies to: 114-122, 124-132


94-103: Good verification of method attachment

This test effectively verifies that the ExpressSessionManager methods are properly attached to the Express request object, which is crucial for the middleware integration.

src/setup/kindeSetupTypes.ts (7)

1-1: Good addition of local KindeGrantType import.

This import aligns with the migration from the deprecated SDK.


10-18: Correct migration to KindeGrantType.

The generic constraint has been properly updated to use KindeGrantType instead of GrantType.


20-25: Correct migration to KindeGrantType enum values.

The interface correctly uses KindeGrantType.AUTHORIZATION_CODE instead of the deprecated GrantType.AUTHORIZATION_CODE.


27-31: Correct migration to KindeGrantType enum values.

The interface correctly uses KindeGrantType.PKCE instead of the deprecated GrantType.PKCE.


33-36: Correct migration to KindeGrantType enum values.

The interface correctly uses KindeGrantType.CLIENT_CREDENTIALS instead of the deprecated GrantType.CLIENT_CREDENTIALS.


42-48: Correct migration to KindeGrantType in conditional type.

The conditional type has been properly updated to use KindeGrantType instead of GrantType in all branches.


2-8: Update deprecated SDK import in src/setup/kindeSetupTypes.ts

This file still pulls types and helpers from the old @kinde-oss/kinde-typescript-sdk, but the PR’s goal is to migrate fully to @kinde/js-utils:

-import type {
-  GrantType,
-  createKindeServerClient,
-  PKCEClientOptions,
-  ACClientOptions,
-  CCClientOptions,
-} from "@kinde-oss/kinde-typescript-sdk";
+import type {
+  GrantType,
+  createKindeServerClient,
+  PKCEClientOptions,
+  ACClientOptions,
+  CCClientOptions,
+} from "@kinde/js-utils";

• File: src/setup/kindeSetupTypes.ts (lines 2–8)
• Ensure that @kinde/js-utils indeed exports these identifiers (or adjust the module/path if they live elsewhere).

@dtoxvanilla1991 dtoxvanilla1991 changed the title Replace deprecated Kinde SDK with js-utils and enhance session management Partially replace deprecated Kinde TS SDK with js-utils ExpressStore and enhance session management Jul 8, 2025
@dtoxvanilla1991 dtoxvanilla1991 force-pushed the feat/js-utils-express-manager branch from 744c0ed to 0c98d32 Compare July 8, 2025 10:37
@dtoxvanilla1991 dtoxvanilla1991 force-pushed the feat/js-utils-express-manager branch from d2296b6 to c28a25c Compare July 24, 2025 00:25
@dtoxvanilla1991 dtoxvanilla1991 requested review from a team as code owners December 22, 2025 01:34
- Replace deprecated Kinde TS SDK session handling with js-utils ExpressStore
- Add @kinde/js-utils dependency (v0.29.0)
- Add sessionManager tests
- Update type definitions for express-session
- Configure pnpm workspace
@dtoxvanilla1991 dtoxvanilla1991 force-pushed the feat/js-utils-express-manager branch from 5ff81bb to c363d68 Compare December 22, 2025 01:42
@dtoxvanilla1991 dtoxvanilla1991 marked this pull request as draft December 22, 2025 01:44
@dtoxvanilla1991
Copy link
Author

dtoxvanilla1991 commented Dec 22, 2025

js-utils first needs to have expressStore aka ExpressSessionManager released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant