-
Notifications
You must be signed in to change notification settings - Fork 260
/
clerkExpressWithAuth.ts
41 lines (36 loc) · 1.2 KB
/
clerkExpressWithAuth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import type { RequestState } from '@clerk/backend/internal';
import { authenticateRequest, setResponseHeaders } from './authenticateRequest';
import type { CreateClerkExpressMiddlewareOptions } from './clerkExpressRequireAuth';
import type { ClerkMiddlewareOptions, MiddlewareWithAuthProp, WithAuthProp } from './types';
export const createClerkExpressWithAuth = (createOpts: CreateClerkExpressMiddlewareOptions) => {
const { clerkClient, secretKey = '', publishableKey = '' } = createOpts;
return (options: ClerkMiddlewareOptions = {}): MiddlewareWithAuthProp => {
return async (req, res, next) => {
let requestState: RequestState;
try {
requestState = await authenticateRequest({
clerkClient,
secretKey,
publishableKey,
req,
options,
});
} catch (e) {
next(e);
return;
}
const err = setResponseHeaders(requestState, res);
if (err || res.writableEnded) {
if (err) {
next(err);
}
return;
}
(req as WithAuthProp<any>).auth = {
...requestState.toAuth(),
claims: requestState.toAuth()?.sessionClaims,
};
next();
};
};
};