Skip to content
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

feat(nextjs): Accept redirectUrl as option for auth().protect() #2329

Merged
merged 7 commits into from
Dec 13, 2023
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()`
panteliselef marked this conversation as resolved.
Show resolved Hide resolved
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
Loading