I am using html and JS with Clerk.js for authentication on my website. I want to redirect users to a specific URL after they successfully log in or sign up. I include the Clerk SDK in my index.html:
<script
async
crossorigin="anonymous"
data-clerk-publishable-key="myKey"
src="https://cdn.jsdelivr.net/npm/@clerk/clerk-js@latest/dist/clerk.browser.js"
type="text/javascript"
>
</script>
I’m initializing Clerk and checking if the user is logged in using the following JavaScript code:
window.addEventListener("load", async function () {
try {
// Initialize Clerk
await Clerk.load();
console.log("ClerkJS is loaded");
// Check if the user is authenticated
if (Clerk.user) {
console.log("User is logged in");
const url = "https://myUrl.com"
window.location.href = url;
} else {
console.log("User is not logged in");
}
} catch (error) {
console.error("Error initializing Clerk:", error);
}
});
I expected Clerk to provide an easy way to configure redirection after a user logs in or signs up, possibly using something like signInForceRedirectUrl or signUpForceRedirectUrl. However, I’m unsure how to implement this functionality with their JavaScript SDK, and I don’t fully understand the documentation on how to handle this specific use case.
I’ve tried manually checking Clerk.user to determine if a user is authenticated and using window.location.href to redirect the user after login or sign-up:
if (Clerk.user) {
console.log("User is logged in");
const url = "https://myUrl.com";
window.location.href = url;
}
However, I want to replace window.location.href with a Clerk method to handle the redirection, whether the user logs in or creates an account. What’s the best way to achieve this using Clerk’s built-in methods or configurations?