Skip to content

fix(backend): Support ExpiresInSeconds param #6150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

jacekradko
Copy link
Member

@jacekradko jacekradko commented Jun 18, 2025

Description

Add Support for expiresInSeconds body param: https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/CreateSessionTokenFromTemplate

Fixes: #6141

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features
    • Added support for specifying token expiration time (in seconds) when generating session tokens.
  • Bug Fixes
    • Improved handling of token creation with or without templates and expiration options.
  • Tests
    • Added comprehensive tests to ensure correct behavior when using the new expiration parameter.
  • Documentation
    • Enhanced documentation and type annotations for token generation options.

Copy link

vercel bot commented Jun 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 18, 2025 3:56pm

Copy link

changeset-bot bot commented Jun 18, 2025

🦋 Changeset detected

Latest commit: 85d17ca

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/backend Patch
@clerk/types Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/localizations Patch
@clerk/clerk-react Patch
@clerk/shared Patch
@clerk/themes Patch
@clerk/vue Patch
@clerk/chrome-extension Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@jacekradko jacekradko marked this pull request as ready for review June 18, 2025 15:45
@jacekradko jacekradko requested review from aeliox, wobsoriano and a team as code owners June 18, 2025 15:45
Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

📝 Walkthrough

Walkthrough

This change introduces support for an optional expiresInSeconds parameter in the sessions.getToken method within the @clerk/backend SDK. The method signature and type definitions are updated to accept this new parameter, allowing callers to specify the expiration time for generated tokens. The implementation is adjusted to include expires_in_seconds in the request body when provided. Associated types in @clerk/types are updated to reflect the new option. Comprehensive tests are added and updated to verify correct behavior when using the new parameter with and without a template.

Assessment against linked issues

Objective Addressed Explanation
Add support for expiresInSeconds parameter to sessions.getToken method (#6141)
Update type definitions to allow expiresInSeconds in backend and types packages (#6141)
Ensure correct request construction and token response handling for new parameter (#6141)
Add or update tests to cover usage of expiresInSeconds in token generation (#6141)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found. All modifications are directly related to the implementation, typing, and testing of the expiresInSeconds parameter in the sessions.getToken method as described in the linked issue.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🔭 Outside diff range comments (1)
packages/backend/src/tokens/authObjects.ts (1)

424-433: createGetToken ignores expiresInSeconds when no template is given

If the caller passes { expiresInSeconds: 3600 } without a template, the current guard (if (options.template)) short-circuits, returning the raw sessionToken and never hitting the backend. This contradicts the new SessionAPI behaviour and the test case “creates a session token without template and with expiresInSeconds”.

Proposed fix:

-    if (options.template) {
-      return fetcher(sessionId, options.template, options.expiresInSeconds);
-    }
-
-    return sessionToken;
+    const needsRemoteToken =
+      options.template !== undefined ||
+      options.expiresInSeconds !== undefined;
+
+    if (needsRemoteToken) {
+      return fetcher(sessionId, options.template, options.expiresInSeconds);
+    }
+
+    return sessionToken;
🧹 Nitpick comments (4)
.changeset/evil-paws-learn.md (1)

6-7: Consider clarifying the changeset summary

A tiny wording tweak will read more naturally and match the tense of other changesets:

-Add Support for expiresInSeconds body param
+Add support for the `expiresInSeconds` body param
packages/backend/src/api/endpoints/SessionApi.ts (1)

94-103: Avoid any in requestOptions

requestOptions is typed as any, defeating TypeScript’s safety. You can keep strictness by re-using the existing RequestOptions type that AbstractAPI.request expects (or declare a minimal interface with method, path, bodyParams?).

-    const requestOptions: any = {
+    const requestOptions: {
+      method: 'POST';
+      path: string;
+      bodyParams?: { expires_in_seconds: number };
+    } = {
       method: 'POST',
       path,
     };
packages/backend/src/tokens/__tests__/authObjects.test.ts (2)

17-20: Improve typing for the mocked createBackendApiClient

vi.mock('../../api/factory', () => ({ createBackendApiClient: vi.fn() })); hides the true call-signature of createBackendApiClient, so IDE/autocomplete assistance and compile-time checks are lost. Prefer re-exporting the original type when stubbing:

-vi.mock('../../api/factory', () => ({
-  createBackendApiClient: vi.fn(),
-}));
+vi.mock('../../api/factory', async () => {
+  const actual = await vi.importActual<typeof import('../../api/factory')>('../../api/factory');
+
+  return {
+    ...actual,
+    createBackendApiClient: vi.fn<Parameters<typeof actual.createBackendApiClient>, ReturnType<typeof actual.createBackendApiClient>>(),
+  };
+});

That way the mock keeps the same parameter / return-type shape, reducing the chance of silent regressions when the real function’s signature changes.


441-516: Consolidate repeated mock setup & ensure isolation

Each it block duplicates the mockGetToken/mockApiClient boot-strap and overrides createBackendApiClient. Consider extracting this into a beforeEach and resetting mocks in an afterEach to keep the tests focused on assertions and avoid accidental state leakage:

-describe('getToken with expiresInSeconds support', () => {
-  it('calls fetcher with expiresInSeconds when template is provided', async () => {
-    const mockGetToken = vi.fn().mockResolvedValue({ jwt: 'mocked-jwt-token' });
-    ...
-  });
-  ...
-});
+describe('getToken with expiresInSeconds support', () => {
+  let mockGetToken: ReturnType<typeof vi.fn>;
+
+  beforeEach(() => {
+    mockGetToken = vi.fn().mockResolvedValue({ jwt: 'mocked-jwt-token' });
+    vi.mocked(createBackendApiClient).mockReturnValue({
+      sessions: { getToken: mockGetToken },
+    } as any);
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+  });
+
+  it('calls fetcher with expiresInSeconds when template is provided', async () => {
+    ...
+  });
+  ...
+});

Benefits:

  • Less duplication – easier to update test fixtures in one place.
  • Guarantees mocks are reset between cases, preventing false positives/negatives if future tests mutate mockGetToken behaviour.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b495279 and 9859375.

📒 Files selected for processing (6)
  • .changeset/evil-paws-learn.md (1 hunks)
  • packages/backend/src/api/__tests__/SessionApi.test.ts (1 hunks)
  • packages/backend/src/api/endpoints/SessionApi.ts (1 hunks)
  • packages/backend/src/tokens/__tests__/authObjects.test.ts (3 hunks)
  • packages/backend/src/tokens/authObjects.ts (2 hunks)
  • packages/types/src/ssr.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/types/src/ssr.ts (1)

18-24: Runtime validation is still advisable

The JSDoc states expiresInSeconds “Must be a positive integer”, but nothing enforces this. Consider adding a runtime guard where the option is first consumed (e.g. in SessionAPI.getToken) to throw early for invalid values.

packages/backend/src/api/__tests__/SessionApi.test.ts (1)

53-68: Great coverage

Nice job adding the edge-case test for “no template but custom expiry”; this will catch the logic gap flagged in createGetToken. 💯

packages/backend/src/tokens/__tests__/authObjects.test.ts (1)

492-515: Missing assertion: verify backend client is not invoked when template is absent

The third test checks that sessions.getToken is untouched, but it would also be valuable to assert that createBackendApiClient itself is never called, ensuring the short-circuit logic really skips any network work:

 expect(mockGetToken).not.toHaveBeenCalled();
+expect(createBackendApiClient).not.toHaveBeenCalled();
 expect(result).toBe('raw-session-token');

This catches accidental regressions where the implementation starts instantiating the API client even when unnecessary.

Comment on lines +398 to 406
type TokenFetcher = (sessionId: string, template: string, expiresInSeconds?: number) => Promise<string>;

/**
* Factory function type that creates a getToken function for auth objects.
*
* @param params - Configuration object containing session information and token fetcher
* @returns A ServerGetToken function that can be used to retrieve tokens
*/
type CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

TokenFetcher should allow omitted template

TokenFetcher currently requires a template: string, but the new API allows sending no template while still supplying expiresInSeconds.
Make template optional to match the actual usage that the tests and SessionAPI permit.

-type TokenFetcher = (sessionId: string, template: string, expiresInSeconds?: number) => Promise<string>;
+type TokenFetcher = (
+  sessionId: string,
+  template?: string,            // may be '', undefined or a real template
+  expiresInSeconds?: number,
+) => Promise<string>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type TokenFetcher = (sessionId: string, template: string, expiresInSeconds?: number) => Promise<string>;
/**
* Factory function type that creates a getToken function for auth objects.
*
* @param params - Configuration object containing session information and token fetcher
* @returns A ServerGetToken function that can be used to retrieve tokens
*/
type CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;
type TokenFetcher = (
sessionId: string,
template?: string, // may be '', undefined or a real template
expiresInSeconds?: number,
) => Promise<string>;
/**
* Factory function type that creates a getToken function for auth objects.
*
* @param params - Configuration object containing session information and token fetcher
* @returns A ServerGetToken function that can be used to retrieve tokens
*/
type CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;
🤖 Prompt for AI Agents
In packages/backend/src/tokens/authObjects.ts around lines 398 to 406, the
TokenFetcher type currently requires the template parameter as a string, but the
new API allows calling it without a template while still providing
expiresInSeconds. To fix this, update the TokenFetcher type definition to make
the template parameter optional by adding a question mark, so it matches the
actual usage in tests and SessionAPI.

Copy link

pkg-pr-new bot commented Jun 18, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6150

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6150

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6150

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6150

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6150

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6150

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6150

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6150

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6150

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6150

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6150

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6150

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6150

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6150

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6150

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6150

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6150

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6150

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6150

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6150

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6150

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6150

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6150

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6150

commit: 85d17ca

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

Successfully merging this pull request may close these issues.

JS Backend SDK sessions.getToken method does not include expires_in_seconds parameter
2 participants