How i should handle the cookie change because of impersonation?

Hey devs! How i should handle the cookie (session) change because of impersonation? Here is my current implementation:
const handleImpersonate = async () => {
setIsLoading(true);
try {
const result = await impersonateUser(userId);
if (result.success) {
toast.success('Successfully impersonated user. You are now logged in as this user.');
router.push("/dashboard")
window.location.reload()
} else {
toast.error(result.error || 'Failed to impersonate user');
}
} catch (error) {
toast.error('An unexpected error occurred');
console.error('Impersonation error:', error);
} finally {
setIsLoading(false);
}
};
const handleImpersonate = async () => {
setIsLoading(true);
try {
const result = await impersonateUser(userId);
if (result.success) {
toast.success('Successfully impersonated user. You are now logged in as this user.');
router.push("/dashboard")
window.location.reload()
} else {
toast.error(result.error || 'Failed to impersonate user');
}
} catch (error) {
toast.error('An unexpected error occurred');
console.error('Impersonation error:', error);
} finally {
setIsLoading(false);
}
};
// Check if current session is impersonated
const isImpersonated = session?.session.impersonatedBy

const handleStopImpersonating = async () => {
setIsLoading(true)
const result = await stopImpersonating()
if (result.success) {
toast.success('Stopped impersonating user')
router.push("/admin/users")
window.location.reload()
}
}
// Check if current session is impersonated
const isImpersonated = session?.session.impersonatedBy

const handleStopImpersonating = async () => {
setIsLoading(true)
const result = await stopImpersonating()
if (result.success) {
toast.success('Stopped impersonating user')
router.push("/admin/users")
window.location.reload()
}
}
6 Replies
shadow
shadowOP2mo ago
actions.ts
export async function impersonateUser(userId: string) {
try {
const result = await auth.api.impersonateUser({
body: {
userId: userId,
},
headers: await headers(),
});

if (!result) {
return { success: false, error: "Failed to impersonate user" };
}

return { success: true, data: result };
} catch (error) {
console.error("Error impersonating user:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Failed to impersonate user"
};
}
}


export async function stopImpersonating() {
try {
await auth.api.stopImpersonating({
headers: await headers(),
});

return { success: true };
} catch (error) {
console.error("Error stopping impersonation:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Failed to stop impersonation"
};
}
}
export async function impersonateUser(userId: string) {
try {
const result = await auth.api.impersonateUser({
body: {
userId: userId,
},
headers: await headers(),
});

if (!result) {
return { success: false, error: "Failed to impersonate user" };
}

return { success: true, data: result };
} catch (error) {
console.error("Error impersonating user:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Failed to impersonate user"
};
}
}


export async function stopImpersonating() {
try {
await auth.api.stopImpersonating({
headers: await headers(),
});

return { success: true };
} catch (error) {
console.error("Error stopping impersonation:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Failed to stop impersonation"
};
}
}
Basically when stopping the impersonation, the session is not being updated to the old session i had before starting the impersonation
FalconiZzare
FalconiZzare2mo ago
You should try window.reload before push. Also im not sure if both works in parallel. I do this and works fine for me (reloads and loads previous session):
const { mutate: handleExitImpersonation } = useMutation({
mutationKey: ["stopImpersonating"],
mutationFn: async () => {
await authClient.admin.stopImpersonating();
},
onSuccess: () => {
window.location.reload();
},
onError: (error) => {
triggerToast(error.message, "error");
}
});
const { mutate: handleExitImpersonation } = useMutation({
mutationKey: ["stopImpersonating"],
mutationFn: async () => {
await authClient.admin.stopImpersonating();
},
onSuccess: () => {
window.location.reload();
},
onError: (error) => {
triggerToast(error.message, "error");
}
});
shadow
shadowOP2mo ago
okay, thanks, one question, do you recoment to use tanstack/query?
FalconiZzare
FalconiZzare2mo ago
Absolutely. It makes hella easier making async call on client components\
shadow
shadowOP2mo ago
I never used it, but i will start using it now, thanks!
FalconiZzare
FalconiZzare2mo ago
Yeha, learn useQuery, useMutation, stale/cache, refetching. It's really useful

Did you find this page helpful?