Skip to content

Commit

Permalink
fix(backend): Fix getToken() from getAuth() return value in v5
Browse files Browse the repository at this point in the history
  • Loading branch information
dimkl committed Jan 10, 2024
1 parent 6b31661 commit fa82747
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 7 deletions.
38 changes: 38 additions & 0 deletions .changeset/eight-cherries-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
'@clerk/backend': major
---

Change `SessionApi.getToken()` to return consistent `{ data, errors }` return value
and fix the `getToken()` from requestState to have the same return behavior as v4
(return Promise<string> or throw error).
This change fixes issues with `getToken()` in `@clerk/nextjs` / `@clerk/remix` / `@clerk/fastify` / `@clerk/sdk-node` / `gatsby-plugin-clerk`:

Example:
```typescript
import { getAuth } from '@clerk/remix';

const { getToken } = await getAuth(...);
const jwtString = await getToken(...);
```

A breaking change introduced is the change of `clerkClient.sessions.getToken()` return value. To keep the existing behavior use the following:
```typescript
import { ClerkAPIResponseError } from '@clerk/shared/error';

const response = await clerkClient.sessions.getToken(...);

if (response.errors) {
const { status, statusText, clerkTraceId } = response;
const error = new ClerkAPIResponseError(statusText || '', {
data: [],
status: Number(status || ''),
clerkTraceId,
});
error.errors = response.errors;

throw error;
}

// the value of the v4 `clerkClient.sessions.getToken(...)`
const jwtString = response.data.jwt;
```
10 changes: 4 additions & 6 deletions packages/backend/src/api/endpoints/SessionApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,9 @@ export class SessionAPI extends AbstractAPI {

public async getToken(sessionId: string, template: string) {
this.requireId(sessionId);
return (
(await this.request<Token>({
method: 'POST',
path: joinPaths(basePath, sessionId, 'tokens', template || ''),
})) as any
).jwt;
return this.request<Token>({
method: 'POST',
path: joinPaths(basePath, sessionId, 'tokens', template || ''),
});
}
}
32 changes: 31 additions & 1 deletion packages/backend/src/tokens/authObjects.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type {
ActClaim,
CheckAuthorizationWithCustomPermissions,
Expand All @@ -10,6 +11,7 @@ import type {

import type { CreateBackendApiOptions } from '../api';
import { createBackendApiClient } from '../api';
import type { ClerkBackendApiResponse } from '../api/request';
import type { AuthenticateContext } from './authenticateContext';

type AuthObjectDebugData = Record<string, any>;
Expand Down Expand Up @@ -73,6 +75,27 @@ const createDebug = (data: AuthObjectDebugData | undefined) => {
};
};

// This helper is introduced as compat layer between the v4 and v5 implementations to keep the
// exposed top-level getToken API the same since it's critical and there are already a lot of
// breaking changes.
// TODO: Revamp AuthObject `getToken()` to return { data, errors } in next major version
const throwResponseErrors = <T>(response: ClerkBackendApiResponse<T>): never => {
// used to by-pass type-safety for the `{ status, statusText, clerkTraceId } = response` line below
if (!response.errors) {
throw new Error('no error to throw');
}

const { status, statusText, clerkTraceId } = response;
const error = new ClerkAPIResponseError(statusText || '', {
data: [],
status: Number(status || ''),
clerkTraceId,
});
error.errors = response.errors;

throw error;
};

/**
* @internal
*/
Expand All @@ -93,7 +116,14 @@ export function signedInAuthObject(
const getToken = createGetToken({
sessionId,
sessionToken: authenticateContext.sessionToken || '',
fetcher: (...args) => apiClient.sessions.getToken(...args),
fetcher: async (...args) => {
const response = await apiClient.sessions.getToken(...args);
if (response.errors) {
return throwResponseErrors(response);
}

return response.data.jwt;
},
});

return {
Expand Down

0 comments on commit fa82747

Please sign in to comment.