Skip to content

chore(astro): Introduce treatPendingAsSignedOut option to server-side utilities #5757

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 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .changeset/sixty-carpets-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
'@clerk/astro': minor
---

Introduce `treatPendingAsSignedOut` option to `getAuth` and `auth` from `clerkMiddleware`

By default, `treatPendingAsSignedOut` is set to `true`, which means pending sessions are treated as signed-out. You can set this option to `false` to treat pending sessions as authenticated.

```ts
// `pending` sessions will be treated as signed-out by default
const { userId } = getAuth(req, locals)
```

```ts
// Both `active` and `pending` sessions will be treated as authenticated when `treatPendingAsSignedOut` is false
const { userId } = getAuth(req, locals, { treatPendingAsSignedOut: false })
```

```ts
clerkMiddleware((auth, context) => {
const { redirectToSignIn, userId } = auth({ treatPendingAsSignedOut: false })

// Both `active` and `pending` sessions will be treated as authenticated when `treatPendingAsSignedOut` is false
if (!userId && isProtectedRoute(context.request)) {
return redirectToSignIn()
}
})
```
5 changes: 3 additions & 2 deletions packages/astro/src/server/clerk-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { isDevelopmentFromSecretKey } from '@clerk/shared/keys';
import { handleNetlifyCacheInDevInstance } from '@clerk/shared/netlifyCacheHandler';
import { isHttpOrHttps } from '@clerk/shared/proxy';
import { handleValueOrFn } from '@clerk/shared/utils';
import type { PendingSessionOptions } from '@clerk/types';
import type { APIContext } from 'astro';

import { authAsyncStorage } from '#async-local-storage';
Expand Down Expand Up @@ -244,8 +245,8 @@ function decorateAstroLocal(clerkRequest: ClerkRequest, context: APIContext, req
context.locals.authStatus = status;
context.locals.authMessage = message;
context.locals.authReason = reason;
context.locals.auth = () => {
const authObject = getAuth(clerkRequest, context.locals);
context.locals.auth = ({ treatPendingAsSignedOut }: PendingSessionOptions = {}) => {
const authObject = getAuth(clerkRequest, context.locals, { treatPendingAsSignedOut });

const clerkUrl = clerkRequest.clerkUrl;

Expand Down
15 changes: 13 additions & 2 deletions packages/astro/src/server/get-auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AuthObject } from '@clerk/backend';
import { AuthStatus, signedInAuthObject, signedOutAuthObject } from '@clerk/backend/internal';
import { decodeJwt } from '@clerk/backend/jwt';
import type { PendingSessionOptions } from '@clerk/types';
import type { APIContext } from 'astro';

import { getSafeEnv } from './get-safe-env';
Expand All @@ -9,7 +10,11 @@ import { getAuthKeyFromRequest } from './utils';
export type GetAuthReturn = AuthObject;

export const createGetAuth = ({ noAuthStatusMessage }: { noAuthStatusMessage: string }) => {
return (req: Request, locals: APIContext['locals'], opts?: { secretKey?: string }): GetAuthReturn => {
return (
req: Request,
locals: APIContext['locals'],
{ treatPendingAsSignedOut = true, ...opts }: { secretKey?: string } & PendingSessionOptions = {},
): GetAuthReturn => {
// When the auth status is set, we trust that the middleware has already run
// Then, we don't have to re-verify the JWT here,
// we can just strip out the claims manually.
Expand Down Expand Up @@ -37,7 +42,13 @@ export const createGetAuth = ({ noAuthStatusMessage }: { noAuthStatusMessage: st

const jwt = decodeJwt(authToken as string);
// @ts-expect-error - TODO: Align types
return signedInAuthObject(options, jwt.raw.text, jwt.payload);
const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload);

if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {
return signedOutAuthObject(options);
}

return authObject;
};
};

Expand Down