Cannot enable two-factor Authentication

Running auth.api.enableTwoFactor gives me a 401 error. How can I resolve this? Versions better-auth: 1.2.2 react-router: 7.2.0 To Reproduce
export async function action({ request }: Route.ActionArgs) {
// ...validate
try {
const { user } = await auth.api.signInEmail({
body: {
email: submission.value.email,
password: submission.value.password,
rememberMe: true,
asResponse: true,
},
});
await auth.api.enableTwoFactor({
body: { password: submission.value.password },
}); // Error in this
const { status } = await auth.api.sendTwoFactorOTP({
body: {
trustDevice: true,
},
});
if (!user.emailVerified) return redirect('/auth/verify-email');
return redirect('/auth/2fa');
} catch (err) {
// error
}
}
export async function action({ request }: Route.ActionArgs) {
// ...validate
try {
const { user } = await auth.api.signInEmail({
body: {
email: submission.value.email,
password: submission.value.password,
rememberMe: true,
asResponse: true,
},
});
await auth.api.enableTwoFactor({
body: { password: submission.value.password },
}); // Error in this
const { status } = await auth.api.sendTwoFactorOTP({
body: {
trustDevice: true,
},
});
if (!user.emailVerified) return redirect('/auth/verify-email');
return redirect('/auth/2fa');
} catch (err) {
// error
}
}
Result
[APIError] {
status: 'UNAUTHORIZED',
body: undefined,
headers: {},
statusCode: 401
}
[APIError] {
status: 'UNAUTHORIZED',
body: undefined,
headers: {},
statusCode: 401
}
3 Replies
bekacru
bekacru2mo ago
it requires a header object
await auth.api.enableTwoFactor({
body: { password: submission.value.password },
headers: //
}); // Error in this
await auth.api.enableTwoFactor({
body: { password: submission.value.password },
headers: //
}); // Error in this
おいしいカップ麺
Thanks for the reply, the same error occurs even after modification.
await auth.api.enableTwoFactor({
headers: request.headers,
body: { password: submission.value.password },
});
await auth.api.enableTwoFactor({
headers: request.headers,
body: { password: submission.value.password },
});
bekacru
bekacru2mo ago
if the user hasn't signed in yet the headers won't contain the cookie. That's why it's still throwing error. I'd recommend calling enable 2fa after the user has signed in. And I suggest calling it fomr the client instead of an action.

Did you find this page helpful?