Skip to content

Commit

Permalink
feat(nextjs): Accept redirectUrl as option for auth().protect()
Browse files Browse the repository at this point in the history
  • Loading branch information
panteliselef committed Dec 12, 2023
1 parent 656d6ae commit c4c8fb8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/thirty-chicken-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/nextjs': patch
---

Accept `redirectUrl` as option for `auth().protect()`
17 changes: 12 additions & 5 deletions packages/nextjs/src/app-router/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type {
CheckAuthorizationParamsWithCustomPermissions,
CheckAuthorizationWithCustomPermissions,
} from '@clerk/types';
import { notFound } from 'next/navigation';
import { notFound, redirect } from 'next/navigation';

import { authAuthHeaderMissing } from '../../server/errors';
import { buildClerkProps, createGetAuth } from '../../server/getAuth';
Expand All @@ -21,6 +21,7 @@ type AuthSignedIn = AuthObjectWithoutResources<
params?:
| CheckAuthorizationParamsWithCustomPermissions
| ((has: CheckAuthorizationWithCustomPermissions) => boolean),
options?: { redirectUrl: string },
) => AuthObjectWithoutResources<SignedInAuthObject>;
}
>;
Expand All @@ -42,12 +43,18 @@ export const auth = () => {
noAuthStatusMessage: authAuthHeaderMissing(),
})(buildRequestLike());

(authObject as AuthSignedIn).protect = params => {
(authObject as AuthSignedIn).protect = (params, options) => {
const handleUnauthorized = (): never => {
if (options?.redirectUrl) {
redirect(options.redirectUrl);
}
notFound();
};
/**
* User is not authenticated
*/
if (!authObject.userId) {
notFound();
return handleUnauthorized();
}

/**
Expand All @@ -64,7 +71,7 @@ export const auth = () => {
if (params(authObject.has)) {
return { ...authObject };
}
notFound();
return handleUnauthorized();
}

/**
Expand All @@ -74,7 +81,7 @@ export const auth = () => {
return { ...authObject };
}

notFound();
return handleUnauthorized();
};

return authObject as AuthSignedIn | AuthSignedOut;
Expand Down

0 comments on commit c4c8fb8

Please sign in to comment.